[英]Filtering on nested array of objects to return the entire matching object
My array of nested objects looks like this along with the array to match it with我的嵌套对象数组以及与之匹配的数组看起来像这样
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"
}
}
]
I want to extract those objects whose templateCode
is Water
.我想提取那些
templateCode
是Water
的对象。 So my final returned array should look like this.所以我最终返回的数组应该是这样的。
let result =
[
{
"code": "a",
"templates": [
{
"templateCode": "Water",
"title": "Earth"
},
{
"templateCode": "Milk",
"title": "Sky"
}
]
},
{
"code": "c",
"templates": [
{
"templateCode": "Water",
"title": "Earth"
},
{
"templateCode": "Tree",
"title": "Moon"
}
}
]
I tried:我试过了:
arrayOfElements.filter(x => x.templates.filter(y => findThis.includes(y.templateCode)));
But it is returning the entire array itself and is not working.但它正在返回整个数组本身并且无法正常工作。
You need to filter
the arrayOfElements
with the condition of any templateCode
existing inside the findThis
array.您需要使用
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.