【问题标题】:How to remove items from an array of objects?如何从对象数组中删除项目?
【发布时间】:2016-08-30 07:07:48
【问题描述】:

如何从对象数组中删除项目? 有一个属性数组,需要从中删除与数组重合的项目。 这是一个例子:

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

不删除给定列表的所有元素。我不明白这是怎么回事。

【问题讨论】:

    标签: javascript jquery arrays typescript


    【解决方案1】:

    您可以使用.filter 函数从数组中获取选定的项目

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

    【讨论】:

      【解决方案2】:

      像这样使用过滤器

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

      【讨论】:

        猜你喜欢
        • 2021-08-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-10
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        • 2021-03-10
        相关资源
        最近更新 更多