我想知道如何使用javascript获取嵌套数组对象中的数组对象。
下面是对象obj
,应该获取children1状态为Active
和Updated
的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
属性执行另一次迭代,访问每个 child
的 children1
属性并过滤它。通过使用新过滤的数组覆盖其 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/