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

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

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

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


当前回答

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

 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);

其他回答

遍历数组,并拼接出不需要的数组。为了更容易使用,向后迭代,这样你就不必考虑数组的活动性质:

for (var i = myArray.length - 1; i >= 0; --i) {
    if (myArray[i].field == "money") {
        myArray.splice(i,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);
}

我们可以使用以下两种方法基于属性删除元素。

使用过滤法

testArray。过滤器(道具=>道具。== '测试值')

采用拼接法。对于这个方法,我们需要找到属性的索引。

const index = testArray。findIndex(道具=>道具。key === '测试值') testArray.splice(指数(1)

一种可能性:

myArray = myArray.filter(function( obj ) {
    return obj.field !== 'money';
});

请注意,过滤器创建了一个新数组。尽管您使用新的引用更新了原始变量myArray,但引用原始数组的任何其他变量都不会得到过滤后的数据。请谨慎使用。

使用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 " > < /脚本>