Alaa
Alaa

Reputation: 167

java script deep searching through a tree with lodash

I have an array with objects like so:

 tree = [
        {
          id: 1,
          name: "parent1",
          children: [
            {
              id: 2,
              name: "child1",
              children: [
                { id: 4, name: "subChild1",dateType:"hijri" },
                { id: 5, name: "subChild2",dateType:"hijri" }
              ]
            },
            { id: 3, name: "child2" }
          ]
        }
      ];

and another array like:

  result=  [{id:4,dateType:"Geo"},{id:5,dateType:"another"}]

i want loop through the second array and for each node in the first array meet the condition id=id ,i need to change the dateType value for it, like this:

 this.result.forEach(res => {
        this.flattenItems(this.tree).find(
          item => item.id == res.id
        ).itemType =res.dateType;
      });

noting that the tree is from 3 levels and the operation only on the last level

Is there any way to implement the loop using lodash?

Upvotes: 2

Views: 269

Answers (1)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

We can do this recursively:

  • First check if the object has a children property. if yes go through the children array and see if the objects have a dateType property.
  • If the children array object don't have a dateType property and instead they have further children call the method again recursively for that children array:

const tree = [{ id: 1, name: "parent1", children: [{ id: 2, name: "child1", children: [{ id: 4, name: "subChild1",dateType:"hijri" }, { id: 5, name: "subChild2",dateType:"hijri" }]}, { id: 3, name: "child2" } ]}];
const result = [{id:4,dateType:"Geo"},{id:5,dateType:"another"}];

const changeDateType = (arr) => {
  if(arr && arr.hasOwnProperty("children")){
      arr.children.forEach(o => {
        if(o.hasOwnProperty("dateType")){
          const child = result.find(d => d.id == o.id);
          o.dateType = child ? child.dateType : o.dateType;
        }
        else{
          changeDateType(o);
        }
      });
  }
  return arr;
}
console.log(tree.map(t => changeDateType(t)));

Upvotes: 1

Related Questions