【问题标题】:Iterate through each object array based on condition check根据条件检查遍历每个对象数组
【发布时间】:2019-04-11 11:25:02
【问题描述】:

我有一个场景是我需要遍历对象中的每个父/子数组。

每个祖父母可以有多个父母,以同样的方式每个父母可以有多个孩子,每个孩子可以有多个子孩子等等。

我需要在迭代时检查类型是“父”还是“子”,然后将 name 属性推送到预期输出中提到的数组。

输入对象:

 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({childType, ...rest}){
  const res = [];
  res.push(rest.name);
  if(childType){
  if(rest.type == "Child")
    res.push(...handleData(childType));
  }
  return res;
}

const res = handleData(inputObject);

预期输出:

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

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

【问题讨论】:

    标签: javascript arrays javascript-objects


    【解决方案1】:

    你可以做一个使用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'));

    【讨论】:

      【解决方案2】:

      您可以使用递归来做到这一点。

      步骤:

      • 创建一个包装函数,在其中声明结果数组。
      • 在其中使包装函数创建一个将被递归调用的函数
      • 检查类型是否与给定类型匹配,将对象的name 添加到结果中
      • 然后检查其childType 中是否存在元素。如果是,则在其每个元素上调用函数。

      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"))

      【讨论】:

        【解决方案3】:

        递归很优雅,但你可以使用 es6 来做,如果对象 childType 非常大,递归可能不适用(堆栈溢出),这里是使用 reduce 的解决方案,

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

        【讨论】:

          【解决方案4】:

          您可以使用递归来解决这个问题。你可以试试这个方法!

          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');

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-04-08
            • 1970-01-01
            • 2013-12-22
            • 2021-12-18
            • 2016-07-02
            • 1970-01-01
            • 2021-02-06
            • 1970-01-01
            相关资源
            最近更新 更多