[英]Filtering on nested array of objects to return the entire matching object
我的嵌套对象数组以及与之匹配的数组看起来像这样
let findThis = ["Water"];
let arrayOfElements =
[
{
"code": "a",
"templates": [
{
"templateCode": "Water",
"title": "Earth"
},
{
"templateCode": "Milk",
"title": "Sky"
}
]
},
{
"code": "b",
"templates": []
},
{
"code": "c",
"templates": [
{
"templateCode": "Water",
"title": "Earth"
},
{
"templateCode": "Tree",
"title": "Moon"
}
},
{
"code": "d",
"templates": [
{
"templateCode": "Tooth",
"title": "Tiger"
}
}
]
我想提取那些templateCode
是Water
的对象。 所以我最终返回的数组应该是这样的。
let result =
[
{
"code": "a",
"templates": [
{
"templateCode": "Water",
"title": "Earth"
},
{
"templateCode": "Milk",
"title": "Sky"
}
]
},
{
"code": "c",
"templates": [
{
"templateCode": "Water",
"title": "Earth"
},
{
"templateCode": "Tree",
"title": "Moon"
}
}
]
我试过了:
arrayOfElements.filter(x => x.templates.filter(y => findThis.includes(y.templateCode)));
但它正在返回整个数组本身并且无法正常工作。
您需要使用findThis
数组中存在的任何templateCode
的条件filter
arrayOfElements
。
let findThis = ["Water"]; let arrayOfElements = [ { "code": "a", "templates": [ { "templateCode": "Water", "title": "Earth" }, { "templateCode": "Milk", "title": "Sky" } ] }, { "code": "b", "templates": [] }, { "code": "c", "templates": [ { "templateCode": "Water", "title": "Earth" }, { "templateCode": "Tree", "title": "Moon" } ] }, { "code": "d", "templates": [ { "templateCode": "Tooth", "title": "Tiger" } ] } ] const result = arrayOfElements.filter(item => item.templates.some(t => findThis.includes(t.templateCode))) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.