javascript - 如何在对象数组的嵌套数组中获取数组对象javascript

标签 javascript arrays json object javascript-objects

我想知道如何使用javascript获取嵌套数组对象中的数组对象。 下面是对象obj,应该获取children1状态为ActiveUpdated的obj。


var obj = [{
   "id": 1,
   "status":"updated",
   "code": "product",
   "children": [
     {
        "id" : 20,
      "title": "cafe",
      "children1": [
        {"id": "2", "title": "SG", "status": "Active"},
        {"id": "3", "title": "TH", "status": "Updated"},
        {"id": "4", "title": "MY", "status": "Deleted"}
      ]
     },
     {
        "id" : 21,
      "title": "others",
      "children1": [
        {"id": "5", "title": "tours", "status": "Active"},
        {"id": "6", "title": "services", "status": "Updated"},
        {"id": "7", "title": "finance", "status": "Deleted"}
      ]
     }
   ]
}]


function getActiveUpdtedObj (obj){
  var result = obj.filter(e=>e.children.filter(i=>i.children1.status !=="Deleted"));
  console.log(result);
}

this.getActiveUpdtedObj(obj);

预期结果

[{
   "id": 1,
   "status":"updated",
   "code": "product",
   "children": [
     {
        "id" : 20,
      "title": "cafe",
      "children1": [
        {"id": "2", "title": "SG", "status": "Active"},
        {"id": "3", "title": "TH", "status": "Updated"}
      ]
     },
     {
        "id" : 21,
      "title": "others",
      "children1": [
        {"id": "5", "title": "tours", "status": "Active"},
        {"id": "6", "title": "services", "status": "Updated"}
      ]
     }
   ]
}]


最佳答案

更新:

因此,首先使用 .map 迭代 obj 数组(它是一个数组,而不是对象),并返回相同的当前对象(使用扩展运算符{...o}),并使用新过滤的 children 数组覆盖 Children 属性。

现在,如何获取这个新过滤的 children 数组?

使用 .map 对当前对象的 .children 属性执行另一次迭代,访问每个 childchildren1 属性并过滤它。通过使用新过滤的数组覆盖其 children1 属性来构造并返回新的子对象(再次使用扩展运算符)。完成,现在您有了新的顶级 children 数组。

obj.map(o => {
  const newChildren = o.children.map(child => {
    const newChildren1 = child.children1.filter(c => c.status !== 'Deleted');
    return { ...child, children1: newChildren1 };
  });

  return { ...o, children: newChildren }
});

关于javascript - 如何在对象数组的嵌套数组中获取数组对象javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60864057/

相关文章:

javascript - 如何以非 Ajax 方式使用 jQuery(或 Javascript)从 API 调用中获取 JSON 结果?

javascript - 读取 .json 文件并解析其数据?

javascript - ( flask ,d3) Uncaught ReferenceError : d3 is not defined

javascript - 使用 underscore.js 展平对象的 javascript 数组

arrays - 反向枚举过滤掉数组中的相似对象

c++ - 重载新的和删除运算符

javascript - 创建依赖下拉列表

javascript - map 调用中的冒号在 Javascript 中意味着什么

javascript - 如何通过 jQuery 传递 id 来渲染部分内容?

javascript - AngularJS promise 错误解析数据