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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15287865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:44:22  来源:igfitidea点击:

Remove array element based on object property

javascriptjqueryarraysobjectproperties

提问by imperium2335

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?

如何根据其属性删除特定的?

e.g. How would I remove the array object with 'money' as the field property?

例如,我将如何删除以 'money' 作为字段属性的数组对象?

回答by jAndy

One possibility:

一种可能:

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

Please note that filtercreates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable myArraywith the new reference. Use with caution.

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

回答by Niet the Dark Absol

Iterate through the array, and spliceout the ones you don't want. For easier use, iterate backwards so you don't have to take into account the live nature of the array:

遍历数组,并splice删除您不想要的数组。为了更容易使用,向后迭代,这样您就不必考虑数组的实时性质:

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

回答by Peracek

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)

回答by Sridhar

You can use lodash's findIndexto 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. Otherwise -1 is returned.

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

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

回答by sifriday

Here's another option using jQuery grep. Pass trueas the third parameter to ensure grep removes items that match your function.

这是使用 jQuery grep 的另一个选项。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.

回答by Supun Kavinda

In ES6, just one line.

在 ES6 中,只有一行。

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

:)

:)

回答by Parth Raval

Using the lodashlibrary:

使用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>

回答by Umair Saleem

Following is the code if you are not using jQuery. Demo

如果您不使用 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);

You can also use underscore library which have lots of function.

您还可以使用具有很多功能的下划线库。

Underscoreis a utility-belt library for JavaScript that provides a lot of the functional programming support

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

回答by Sandeep sandy

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 truemeans will return an array of elements which fails your function logic, falsemeans will return an array of elements which fails your function logic.

元素是数组中的一个对象。第三个参数true意味着将返回一个使函数逻辑失败的元素数组,false意味着将返回一个使函数逻辑失败的元素数组。

回答by HymanTheKnife

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