How to remove array objects having property

时间秒杀一切 提交于 2019-12-23 04:04:11

问题


What is the easiest way to remove all objects from an array with a particular property = x?


回答1:


Use _.filter

var result = _.filter(arr, function(item) {
  return !("prop" in item);
});

If you want to limit it to the immediate properties of each item, use

var result = _.filter(arr, function(item) {
  return !item.hasOwnProperty("prop");
});



回答2:


It seems like the easiest way would be to use the filter method:

var newArray = _.filter(oldArray, function(x) { return !('prop' in x); });
// or
var newArray = _.filter(oldArray, function(x) { return !_.has(x, 'prop'); });

Or alternatively, the reject method should work just as well:

var newArray = _.reject(oldArray, function(x) { return 'prop' in x; });
// or
var newArray = _.reject(oldArray, function(x) { return _.has(x, 'prop'); });

Update Given your updated question, the code should look like this:

var newArray = _.filter(oldArray, function(x) { return x.property !== 'value'; });

Or like this

var newArray = _.reject(oldArray, function(x) { return x.property === 'value'; });


来源:https://stackoverflow.com/questions/20738516/how-to-remove-array-objects-having-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!