PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

[FIXED] How to make a method that finds every object by id in angular

 July 25, 2022     angular, javascript, json     No comments   

Issue

Please help,

I want to make a method findChildByIdInData(data:any, childId:string) where the data is any JSON main node that has children with Ids.

Simply, how to make a method that receives JsonNode and its child Id as parameters to find that object using angular.

In my case, I have a data as a node where I want to find its children's objects (may be nested) by id.

Thanks for your time :)


Solution

Got the result by using the Recursively Traverse an Object method: this link helps me: https://cheatcode.co/tutorials/how-to-recursively-traverse-an-object-with-javascript.

the backendService:

// Verify the object
     isObject(value): any {
        return !!(value && typeof value === "object");
      };

      // Find object in node
      findNestedObject(object: {}, keyToMatch: String, valueToMatch: String): any {
        if (this.isObject(object)) {
          let entries = Object.entries(object);
      
          for (let i = 0; i < entries.length; i += 1) {
            const [objectKey, objectValue] = entries[i];
      
            if (objectKey === keyToMatch && objectValue === valueToMatch) {
              return object;
            }
      
            if (this.isObject(objectValue)) {
              let child = this.findNestedObject(objectValue, keyToMatch, valueToMatch);
      
              if (child !== null) {
                return child;
              }
            }
          }
        }
      
        return null;
      };

and call that method in component as:

 // Find the nested object by passing node, key, & value
        // the this.shop is your backend data or json  
        let  result = this.backendService.findNestedObject(this.data, "id", "dataId");
        console.log("Result: ", result);


Answered By - ftslaptop pc
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing