Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/466.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 遍历对象数组_Javascript_Arrays_Recursion - Fatal编程技术网

Javascript 遍历对象数组

Javascript 遍历对象数组,javascript,arrays,recursion,Javascript,Arrays,Recursion,我需要遍历对象数组,直到子键中有值为止 数组中的每个对象都有一个子数组,我需要检查每个对象中是否存在timeGroupName 最后,如果任何对象中缺少timeGroupName,则返回指示timeGroupName不存在的内容。我想在这里使用递归 示例对象: [ { name: "vimlesh", timeGroupName: "NupurGroup", type: "node", id: 1592208617196, children: [

我需要遍历对象数组,直到子键中有值为止

数组中的每个对象都有一个子数组,我需要检查每个对象中是否存在
timeGroupName

最后,如果任何对象中缺少
timeGroupName
,则返回指示
timeGroupName
不存在的内容。我想在这里使用递归

示例对象:

[
  {
    name: "vimlesh",
    timeGroupName: "NupurGroup",
    type: "node",
    id: 1592208617196,
    children: [
      {
        name: "sid",
        timeGroupName: "NupurGroup",
        type: "node",
        id: 1592210050837,
        children: [
          {
            name: "rush",
            timeGroupName: "NupurGroup",
            type: "node",
            id: 1592210076303,
            children: []
          },
          {
            name: "1",
            timeGroupName: "NupurGroup",
            type: "store",
            storeId: "5c46e5fde6d3c2293e1f53b6",
            id: 1592210057381,
            children: []
          }
        ],
        collapsedStore: false,
        collapsedGroup: false
      }
    ],
    collapsedGroup: false
  }
];

您可以使用此递归函数:

const findMissing = data => (data || []).flatMap(item => 
    ("timeGroupName" in item ? [] : [item.id]).concat(findMissing(item.children)) 
);

这将返回一个数组,其中包含没有“timeGroupName”属性的所有对象的id值。在您的示例中,所有对象都有它,因此上述函数将为它返回
[]

您可以使用此递归函数:

const findMissing = data => (data || []).flatMap(item => 
    ("timeGroupName" in item ? [] : [item.id]).concat(findMissing(item.children)) 
);

这将返回一个数组,其中包含没有“timeGroupName”属性的所有对象的id值。在您的示例中,所有对象都有它,因此上面的函数将为它返回
[]

到目前为止您尝试了什么?到目前为止您尝试了什么?