繁体   English   中英

过滤嵌套的对象数组以返回整个匹配的对象

[英]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"
                 }
            }
    ]

我想提取那些templateCodeWater的对象。 所以我最终返回的数组应该是这样的。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM