【问题标题】:How do I filter an array object inside of a array of objects Javascript?如何在对象数组Javascript中过滤数组对象?
【发布时间】:2021-04-23 08:37:57
【问题描述】:

我正在尝试按产品

过滤列表
const questions = [
    { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]},
    { "id": 1505, "offerings": [{"code": "AA"},{"code": "ABC"}]},
    { "id": 1500, "offerings": [{"code": "AC"},{"code": "DC"}]}
];

const filterByArray = ['AB', 'DC'];

我的预期结果是根据 filterByArray 中传递的内容取回所有数组元素

[
    { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]},
    { "id": 1500, "offerings": [{"code": "AC"},{"code": "DC"}]}
]

我尝试使用过滤数组

var filtered = questions.filter(function(element) {
    return element.offerings.filter(function(cd) {
       return filterByArray.indexOf(cd.code) > -1;
    }).length === filterByArray.length;
});

console.log(filtered)

但这会继续返回所有数组元素。

【问题讨论】:

    标签: javascript arrays typescript filtering


    【解决方案1】:

    使用Array.some()Array.includes()

    const questions = [
        { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]},
        { "id": 1505, "offerings": [{"code": "AA"},{"code": "ABC"}]},
        { "id": 1500, "offerings": [{"code": "AC"},{"code": "DC"}]}
    ];
    
    const filterByArray = ['AB', 'DC'];
    
    const output = questions.filter(q => q.offerings.some(o => filterByArray.includes(o.code)));
    
    console.log(output);

    【讨论】:

      猜你喜欢
      • 2022-10-14
      • 1970-01-01
      • 2018-11-22
      • 2020-07-03
      • 1970-01-01
      • 2012-11-15
      • 2020-08-27
      相关资源
      最近更新 更多