我有一个这样的对象数组:

var myArray = [
    {field: 'id', operator: 'eq', value: id}, 
    {field: 'cStatus', operator: 'eq', value: cStatus}, 
    {field: 'money', operator: 'eq', value: money}
];

我如何删除一个特定的基于它的属性?

例:我该如何移除以“money”作为字段属性的数组对象?


当前回答

var myArray = [
    {field: 'id', operator: 'eq', value: id}, 
    {field: 'cStatus', operator: 'eq', value: cStatus}, 
    {field: 'money', operator: 'eq', value: money}
];
console.log(myArray.length); //3
myArray = $.grep(myArray, function(element, index){return element.field == "money"}, true);
console.log(myArray.length); //2

Element是数组中的一个对象。 第三个参数true表示将返回一个元素数组,这个数组不符合你的函数逻辑,false表示将返回一个元素数组,这个数组不符合你的函数逻辑。

其他回答

var myArray = [
    {field: 'id', operator: 'eq', value: id}, 
    {field: 'cStatus', operator: 'eq', value: cStatus}, 
    {field: 'money', operator: 'eq', value: money}
];
console.log(myArray.length); //3
myArray = $.grep(myArray, function(element, index){return element.field == "money"}, true);
console.log(myArray.length); //2

Element是数组中的一个对象。 第三个参数true表示将返回一个元素数组,这个数组不符合你的函数逻辑,false表示将返回一个元素数组,这个数组不符合你的函数逻辑。

您可以使用lodash的findIndex获取特定元素的索引,然后使用它进行拼接。

myArray.splice(_.findIndex(myArray, function(item) {
    return item.value === 'money';
}), 1);

更新

你也可以使用ES6的findIndex()

findIndex()方法返回数组中满足所提供测试函数的第一个元素的索引。否则返回-1。

const itemToRemoveIndex = myArray.findIndex(function(item) {
  return item.field === 'money';
});

// proceed to remove an item only if it exists.
if(itemToRemoveIndex !== -1){
  myArray.splice(itemToRemoveIndex, 1);
}

下面是使用jQuery grep的另一个选项。传递true作为第三个参数,以确保grep删除与函数匹配的项。

users = $.grep(users, function(el, idx) {return el.field == "money"}, true)

如果你已经在使用jQuery,那么不需要填充,这可能比使用Array.filter有用。

使用lodash库:

var myArray = [ {字段:'id',运算符:'eq',值:'id'}, {字段:'cStatus',运算符:'eq',值:'cStatus'}, {字段:'money',运算符:'eq',值:'money'} ]; var newArray = _。remove(myArray, function(n) { 返回n.value === 'money';; }); console.log(“数组”); console.log (myArray); console.log(“新数组”); console.log (newArray); < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js " > < /脚本>

假设您想通过其field属性删除第二个对象。

用ES6就这么简单。

myArray.splice(myArray.findIndex(item => item.field === "cStatus"), 1)