我有一个包含多个对象的数组,如下所示。如何删除包含特定值的完整对象。
var cars= [
{key: 'browser', label: 'Chrome'},
{key: 'browser', label: 'Firefox'},
{key: 'browser', label: 'Safari'}
];
例如,要删除的对象是包含标签 chrome 和 safari 的对象。
我遇到过一维值数组的示例,但这是一个对象数组。
最佳答案
您可以使用Array.prototype.filter仅返回某些值或仅排除某些值。
var cars = [
{key: 'browser', label: 'Chrome'},
{key: 'browser', label: 'Firefox'},
{key: 'browser', label: 'Safari'}
];
// Filter by only the thing you want
var firefoxOnly = cars.filter(function(item) {
return item.label === 'Firefox';
});
console.log(firefoxOnly);
// filter out the things you don't want
var notChromeSafari = cars.filter(function(item) {
return item.label !== 'Chrome' && item.label !== 'Safari';
});
console.log(notChromeSafari);
// or make a set of exclusions to filter out things you don't want
// you could also make this a list of inclusions,
// it would be the inverse of this. I'll leave that as an exercise for the reader.
var exclusions = ['Chrome', 'Safari'];
var filtered = cars.filter(function(item) {
// only return items that are not in the exclusion list
return exclusions.indexOf(item.label) === -1;
});
console.log(filtered);
关于javascript - 如何从数组中删除具有给定属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40570447/