javascript - 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.
解决方案
使用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);
推荐阅读
- php - spl_auload_register 排除嵌套类 - PHP
- php - 将 Python 输出发送到 HTML 字段
- javascript - 图像显示取决于参数
- angular - AgGrid - 如何将我的行选择与属性绑定
- reactjs - 在 reactjs 中使用状态和映射时出错
- java - Android 程序因空指针异常而崩溃
- plot - 如何在 Mathematica 中向矢量图添加水平线(平衡)
- security - 如何在电话号码验证过程中过滤掉虚拟 SIM 卡用户?
- angular - 如何使用角度日期管道转换 Firebase 时间戳
- installation - 在 WIX 升级期间重新启动 Windows 服务