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

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

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

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


当前回答

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

使用过滤法

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

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

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

其他回答

如果不使用jQuery,下面是代码。演示

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

alert(myArray.length);

for(var i=0 ; i<myArray.length; i++)
{
    if(myArray[i].value=='money')
        myArray.splice(i);
}

alert(myArray.length);

你也可以使用下划线库,它有很多功能。

Underscore是JavaScript的一个实用带库,提供了大量的函数式编程支持

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

使用过滤法

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

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

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

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

用ES6就这么简单。

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

在ES6中,只有一行。

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

:)

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