Home > Mobile >  How to make a method that finds every object by id in angular
How to make a method that finds every object by id in angular

Time:05-15

Please help,

I want to make a method findChildByIdInShop(shop:any, childId:string) where the shop 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 shop as a node where I want to find its children's objects (may be nested) by id.

Thanks for your time :)

Back end Service

createShop(id: string): any {
    let shop: any = {};
    shop.id = id;
    shop.departmentList = [];

    let dep1: any = {};
    dep1.id = "d1"
    dep1.name = "my department 1";
    shop.departmentList.push(dep1);

    let dep2: any = {};
    dep2.id = "d2"
    dep2.name = "my department 2";
    dep2.departmentVariationList = [];
    let dep2v1: any = {};
    dep2v1.id = "dep2v1"
    dep2v1.name = "my department variation dep2v1";
    dep2.departmentVariationList.push(dep2v1);
    //shop.departmentList.push(dep2);
    let dep2v2: any = {};
    dep2v2.id = "dep2v2"
    dep2v2.name = "my department variation dep2v2";
    dep2.departmentVariationList.push(dep2v2);
    shop.departmentList.push(dep2);

    let dep3: any = {};
    dep3.id = "d3"
    dep3.name = "my department 3";
    shop.departmentList.push(dep3);

    return shop;
  }

Find Any Child in Shop By its Id method In backend service:

  findChildByIdInShop(shop:any, childId:string):any[]{
   // how to implement this
  }

What I have tried but no result:

findNodeInArray(array:any,id:string):any{
        let node:any;
        for(let i=0; i<array.length; i  ){
            let n=array[i];
    
            if(n.id == id) {
              node= n;
              break;
            }
    
            for (const k in n) {
                const v = n[k];
                if(v instanceof Array){
                    this.findNodeInArray(v, id);
                }
            }
        }
        return node;
      }
    
      findNode(parentNode:any,id:string):any {
          if (parentNode instanceof Array) {
              this.findNodeInArray(parentNode, id);
          }
          for (const k in parentNode) {
              const v = parentNode[k];
              if(v instanceof Array){
                  this.findNodeInArray(v, id);
              }
              else { return "Undefined";}
          }
      } 

In Front Component :

        let shop: any = this.backendService.createShop("shop1");
    
        let node: any = this.backendService.findNode(shop, "dep2v2");
        let node2: any = this.backendService.findNode(shop, "dep2v1");
        console.log(JSON.stringify("Shop1 node", node));
        console.log(JSON.stringify("Shop2 node", node2));

CodePudding user response:

To implement lodash

https://stackoverflow.com/a/41992126/18762612

import { get } from "lodash";

variable in component

deepObj = {a:{b:{n:{e:100, c: 120}}} 

example of get

constructor(){
 get(deepObj, 'a.b.n.e');
}

CodePudding user response:

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.shop, "id", "dep2v2");
        console.log("Result: ", result);
  • Related