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

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

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

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


当前回答

您可以使用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);
}

其他回答

在ES6中,只有一行。

const arr = arr.filter(item => item.key !== "some value");

:)

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

用ES6就这么简单。

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

您可以使用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);
}

基于上面的一些注释,下面是如何根据键名和键值删除对象的代码

 var items = [ 
  { "id": 3.1, "name": "test 3.1"}, 
  { "id": 22, "name": "test 3.1" }, 
  { "id": 23, "name": "changed test 23" } 
  ]

    function removeByKey(array, params){
      array.some(function(item, index) {
        return (array[index][params.key] === params.value) ? !!(array.splice(index, 1)) : false;
      });
      return array;
    }

    var removed = removeByKey(items, {
      key: 'id',
      value: 23
    });

    console.log(removed);
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表示将返回一个元素数组,这个数组不符合你的函数逻辑。