用数组值过滤数组对象
filter array object with array value
我正在尝试用数组值过滤一个数组对象,这里是代码:
const array1 = [{
"packaging": "Box",
"price": "100"
}, {
"packaging": "Pcs",
"price": "15",
}, {
"packaging": "Item",
"price": "2",
}];
const b = ['Pcs','Item']
const found = array1.filter(el => {
for(i = 0; i < b.length; i++) {
return el.packaging !== b[i];
}
});
console.log(found);
我预期的输出是数组,对象在 b 中不存在
[{ packaging: "Box", price: "100" }]
改为使用 .includes
检查:
const array1 = [{
"packaging": "Box",
"price": "100"
}, {
"packaging": "Pcs",
"price": "15",
}, {
"packaging": "Item",
"price": "2",
}];
const b = ['Pcs','Item']
const found = array1.filter(el => !b.includes(el.packaging));
console.log(found);
您应该执行以下操作,
const array1 = [{
"packaging": "Box",
"price": "100"
}, {
"packaging": "Pcs",
"price": "15",
}, {
"packaging": "Item",
"price": "2",
}];
const b = ['Pcs','Item']
const found = array1.filter(el => {
return b.findIndex(item => item === el.packaging) <= -1;
});
console.log(found);
这是否解决了您的问题?
const arr1 = [
{"packaging": "Box", "price": "100"},
{"packaging": "Pcs", "price": "15"},
{"packaging": "Item", "price": "2"}
];
const arr2 = ['Pcs','Item'];
const found = arr1.filter(item => {
return arr2.indexOf(item.packaging) === -1;
});
console.log(found);
我正在尝试用数组值过滤一个数组对象,这里是代码:
const array1 = [{
"packaging": "Box",
"price": "100"
}, {
"packaging": "Pcs",
"price": "15",
}, {
"packaging": "Item",
"price": "2",
}];
const b = ['Pcs','Item']
const found = array1.filter(el => {
for(i = 0; i < b.length; i++) {
return el.packaging !== b[i];
}
});
console.log(found);
我预期的输出是数组,对象在 b 中不存在 [{ packaging: "Box", price: "100" }]
改为使用 .includes
检查:
const array1 = [{
"packaging": "Box",
"price": "100"
}, {
"packaging": "Pcs",
"price": "15",
}, {
"packaging": "Item",
"price": "2",
}];
const b = ['Pcs','Item']
const found = array1.filter(el => !b.includes(el.packaging));
console.log(found);
您应该执行以下操作,
const array1 = [{
"packaging": "Box",
"price": "100"
}, {
"packaging": "Pcs",
"price": "15",
}, {
"packaging": "Item",
"price": "2",
}];
const b = ['Pcs','Item']
const found = array1.filter(el => {
return b.findIndex(item => item === el.packaging) <= -1;
});
console.log(found);
这是否解决了您的问题?
const arr1 = [
{"packaging": "Box", "price": "100"},
{"packaging": "Pcs", "price": "15"},
{"packaging": "Item", "price": "2"}
];
const arr2 = ['Pcs','Item'];
const found = arr1.filter(item => {
return arr2.indexOf(item.packaging) === -1;
});
console.log(found);