首页 > 解决方案 > How do I filter an array object inside of a array of objects Javascript?

问题描述

I am trying to filter the list by offerings

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'];

My expected outcome is to get back all the array elements based on what's passed in filterByArray

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

I tried filtering the array using

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

console.log(filtered)

But this keep returning all array elements.

标签: javascriptarraystypescriptfiltering

解决方案


使用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);


推荐阅读