我想,以滤除列表产品
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)
但这会继续返回所有数组元素。
使用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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句