简体   繁体   中英

How to remove items from an array of objects?

How to remove items from an array of objects? There is an array of properties per which it is necessary to remove items from which isn isn coincides with the array. Here is an example:

let selectedIsn = [10,15,20,30,40];
let arayObject = [{
  isn:10,
  name:"Bolt"
}, {
  isn:13,
  name:"marry"
},{
  isn:15,
  name:"a"
},{
  isn:18,
  name:"q"
}, {
  isn:20,
  name:"marrys"
},{
  isn:25,
  name:"aa"
},{
  isn:30,
  name:"qa"
}, {
  isn:40,
  name:"marrya"
},{
  isn:55,
  name:"sa"
},{
  isn:68,
  name:"qas"
 }];

let deleteSelected = (q,selectedItems) => {
        let arrayNew = q,
            count=0;

    for (var m = 0; m < q.length; m++) {
        let index = selectedItems.indexOf(q[m]["isn"]);
        if (index > -1) {
            arrayNew.splice(m - count, 1);
            count++;
        }
    }
    return arrayNew;
}

deleteSelected(arayObject,selectedIsn);

Removes not all elements of the given list. I do not understand what's wrong doing.

You can use .filter function to get selected items from array

let deselected = arayObject.filter(function (a) {
   return selectedIsn.indexOf(a.isn) < 0;
});

像这样使用过滤器

var result = arayObject.filter(item => selectedIsn.indexOf(item.isn)===-1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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