简体   繁体   中英

Iterate through each object array based on condition check

I have a scenario were I need to iterate through each parent/child array in an object.

Each Grandparents can have multiple parents, in same fashion each parent can have multiple childs, each child can have multiple subChilds and so on.

I need to check if type is "parent" or "child" while iterating and then push name property to an array as mentioned in expected output.

Input Object:

 var inputObject = {
  "id": 1,
  "name": "Grand Parent 1",
  "type": "GrandParent",
  "childType": [
   {
     "id": 2,
     "type": "Parent",
     "childType": [
    {
      "id": 3,
      "type": "Child",
      "childType": [],
      "name": "Child 11"
    },
    {
      "id": 4,
      "type": "Child",
      "childType": [],
      "name": "Child 12"
    }
  ],
  "name": "Parent 1"
},
{
  "id": 5,
  "type": "Parent",
  "childType": [
    {
      "id": 6,
      "type": "Child",
      "childType": [],
      "name": "Child 21"
    }
  ],
  "name": "Parent 2"
},
{
  "id": 7,
  "type": "Parent",
  "childType": [
    {
      "id": 8,
      "type": "Child",
      "childType": [],
      "name": "Child 31"
    }
  ],
  "name": "Parent 3"
}
 ]
 }

Code Tried:

 function handleData({childType, ...rest}){
  const res = [];
  res.push(rest.name);
  if(childType){
  if(rest.type == "Child")
    res.push(...handleData(childType));
  }
  return res;
}

const res = handleData(inputObject);

Expected Output:

If type selected is "Parent"
["Parent 1", "Parent 2, Parent 3"]

if type selected is "Child"
["Child 11", "Child 12", "Child 21", "Child 31"]

You can do a recursive function that uses flatMap() :

 const obj = {id:1,name:"Grand Parent 1",type:"GrandParent",childType:[{id:2,type:"Parent",childType:[{id:3,type:"Child",childType:[],name:"Child 11"},{id:4,type:"Child",childType:[],name:"Child 12"}],name:"Parent 1"},{id:5,type:"Parent",childType:[{id:6,type:"Child",childType:[],name:"Child 21"}],name:"Parent 2"},{id:7,type:"Parent",childType:[{id:8,type:"Child",childType:[],name:"Child 31"}],name:"Parent 3"}]}; const get = (o, t) => o.type === t ? [o.name] : o.childType.flatMap(c => get(c, t)); console.log(get(obj, 'GrandParent')); console.log(get(obj, 'Parent')); console.log(get(obj, 'Child')); 

You can do that using recursion.

Steps:

  • Create a wrapper function in which you declare result array.
  • Inside that make a wrapper function create a function which would be called recursively
  • Check if type matches the given type add the name of object to result
  • Then check if elements exists in its childType . If yes yes then call function on each each of its element.

 var inputObject = { "id": 1, "name": "Grand Parent 1", "type": "GrandParent", "childType": [ { "id": 2, "type": "Parent", "childType": [ { "id": 3, "type": "Child", "childType": [], "name": "Child 11" }, { "id": 4, "type": "Child", "childType": [], "name": "Child 12" } ], "name": "Parent 1" }, { "id": 5, "type": "Parent", "childType": [ { "id": 6, "type": "Child", "childType": [], "name": "Child 21" } ], "name": "Parent 2" }, { "id": 7, "type": "Parent", "childType": [ { "id": 8, "type": "Child", "childType": [], "name": "Child 31" } ], "name": "Parent 3" } ] } function handleData(obj,type){ let res = []; function recursive(obj){ if(type === obj.type) res.push(obj.name); if(obj.childType.length){ obj.childType.forEach(a => recursive(a)); } } recursive(obj) return res; } console.log(handleData(inputObject,"Child")) console.log(handleData(inputObject,"Parent")) 

Recursion is elegant but you could use es6 to do it , if the object childType was very large, recursion might not be applicable (stack overflow), here is a solution using reduce,

function getType({childType}, type) {
  return childType.reduce( (acc, {type: objectType, name}) => { 
   if (objectType === type){
     acc.push(name)
   }
   return acc
  }, [])
}

You can solve this problem using recursion. You can try on this way !

 var inputObject = { "id": 1, "name": "Grand Parent 1", "type": "GrandParent", "childType": [ { "id": 2, "type": "Parent", "childType": [ { "id": 3, "type": "Child", "childType": [], "name": "Child 11" }, { "id": 4, "type": "Child", "childType": [], "name": "Child 12" } ], "name": "Parent 1" }, { "id": 5, "type": "Parent", "childType": [ { "id": 6, "type": "Child", "childType": [], "name": "Child 21" } ], "name": "Parent 2" }, { "id": 7, "type": "Parent", "childType": [ { "id": 8, "type": "Child", "childType": [], "name": "Child 31" } ], "name": "Parent 3" } ] }; var resultValues = []; function getResult(inputObject, propertyName, propertyValue) { for (var objectProperty in inputObject) { if (objectProperty == propertyName && inputObject[objectProperty] == propertyValue) { resultValues.push(inputObject['name']); console.log(resultValues); } else { if (objectProperty == 'childType') { inputObject[objectProperty].forEach(function (element) { getResult(element, propertyName, propertyValue) }); } } } //console.log(resultValues); } getResult(inputObject, 'type', 'GrandParent'); getResult(inputObject, 'type', 'Parent'); getResult(inputObject, 'type', 'Child'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM