简体   繁体   English

根据对象属性删除数组元素

[英]Remove array element based on object property

I have an array of objects like so:我有一个像这样的对象数组:

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

How do I remove a specific one based on its property?如何根据其属性删除特定的?

eg How would I remove the array object with 'money' as the field property?例如,我将如何删除以 'money' 作为字段属性的数组对象?

One possibility:一种可能:

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

Please note that filter creates a new array.请注意filter会创建一个新数组。 Any other variables referring to the original array would not get the filtered data although you update your original variable myArray with the new reference.尽管您使用新引用更新了原始变量myArray ,但引用原始数组的任何其他变量都不会获得过滤后的数据。 Use with caution.谨慎使用。

Iterate through the array, and splice out the ones you don't want.遍历数组, splice出你不想要的。 For easier use, iterate backwards so you don't have to take into account the live nature of the array:为了更容易使用,向后迭代,这样您就不必考虑数组的实时性质:

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

Say you want to remove the second object by it's field property.假设您想通过它的 field 属性删除第二个对象。

With ES6 it's as easy as this.使用 ES6 就这么简单。

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

In ES6, just one line.在 ES6 中,只有一行。

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

:) :)

You can use lodash's findIndex to get the index of the specific element and then splice using it.可以使用 lodash 的findIndex获取特定元素的索引,然后拼接使用。

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

Update更新

You can also use ES6's findIndex()你也可以使用 ES6 的findIndex()

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。 Otherwise -1 is returned.否则返回-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);
}

Here's another option using jQuery grep.这是使用 jQuery grep 的另一个选项。 Pass true as the third parameter to ensure grep removes items that match your function.true作为第三个参数传递以确保 grep 删除与您的函数匹配的项目。

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

If you're already using jQuery then no shim is required, which is could be useful as opposed to using Array.filter .如果您已经在使用 jQuery,则不需要 shim,这可能比使用Array.filter有用。

We can remove the element based on the property using the below 2 approaches.我们可以使用以下 2 种方法根据属性删除元素。

  1. Using filter method使用过滤方法
testArray.filter(prop => prop.key !== 'Test Value')
  1. Using splice method.采用拼接法。 For this method we need to find the index of the propery.对于这种方法,我们需要找到属性的索引。
 const index = testArray.findIndex(prop => prop.key === 'Test Value') testArray.splice(index,1)
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 is an object in the array.元素是数组中的一个对象。 3rd parameter true means will return an array of elements which fails your function logic, false means will return an array of elements which fails your function logic.第三个参数true表示将返回一个使函数逻辑失败的元素数组, false表示将返回一个使函数逻辑失败的元素数组。

Using the lodash library:使用lodash库:

 var myArray = [ {field: 'id', operator: 'eq', value: 'id'}, {field: 'cStatus', operator: 'eq', value: 'cStatus'}, {field: 'money', operator: 'eq', value: 'money'} ]; var newArray = _.remove(myArray, function(n) { return n.value === 'money';; }); console.log('Array'); console.log(myArray); console.log('New Array'); console.log(newArray);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

Based on some comments above below is the code how to remove an object based on a key name and key value基于上面的一些评论,下面是如何根据键名和键值删除对象的代码

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

jAndy's solution is probably best, but if you can't rely on filter you could do something like: jAndy 的解决方案可能是最好的,但如果您不能依赖过滤器,您可以执行以下操作:

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

myArray.remove_key = function(key){
    var i = 0, 
        keyval = null;
    for( ; i < this.length; i++){
        if(this[i].field == key){
            keyval = this.splice(i, 1);
            break;
        }
    }
    return keyval;
}

Following is the code if you are not using jQuery.如果您不使用 jQuery,以下是代码。 Demo演示

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

You can also use underscore library which have lots of function.您还可以使用具有很多功能的下划线库。

Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support Underscore是一个实用的 JavaScript 库,它提供了大量的函数式编程支持

使用 lodash 库很简单

_.remove(myArray , { field: 'money' });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM