我有一个这样的数组:
const array = [
{
id: 1,
list: [
{
name: "abc",
quantity: 46,
},
{
name: "abc cba",
quantity: 8,
},
]
}
{
id: 2,
list: [
{
name: "def",
quantity: 895,
},
{
name: "abc ebn",
quantity: 8,
},
]
}
]
如果我想检查该数组是否包含:name: "abc"
并仅过滤包含它的对象,过滤该数组的最佳方法是什么?
我试过在 filter() 中使用 map.(),但我不知道这样做是否合适。 我的代码是这样的:
let filteredArray = array.filter(el => {
let filteredName;
el.list.map (name => {
if (elt.name.includes("abc"){
filteredName = name
}
}
return filteredName;
})
最佳答案
const array = [
{ id: 1, list: [ { name: "abc", quantity: 46, }, { name: "abc cba", quantity: 8 } ] },
{ id: 2, list: [ { name: "def", quantity: 895, }, { name: "abc ebn", quantity: 8 } ] }
];
// iterate over array
const res = array.map(({ list, ...el }) => (
// filter current element's list
{ ...el, list: list.filter(({ name }) => name.includes("abc")) }
));
console.log(res);
关于javascript - 在另一个对象数组中过滤一个对象数组的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68246738/