使用filter()函数

时间:2018-03-10 21:44:38

标签: javascript vue.js

我一直在尝试删除嵌套数组中带有ID的元素。

我不确定如何将filter()与嵌套数组一起使用。

我只想删除{id: 111,name: "A"}对象。

这是我的代码:

var array = [{
    id: 1,
    list: [{
        id: 123,
        name: "Dartanan"
    }, {
        id: 456,
        name: "Athos"
    }, {
        id: 789,
        name: "Porthos"
    }]
}, {
    id: 2,
    list: [{
        id: 111,
        name: "A"
    }, {
        id: 222,
        name: "B"
    }]
}]

var temp = array
for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array[i].list.length; j++) {
        temp = temp.filter(function(item) {
            return item.list[j].id !== 123
        })
    }
}
array = temp

3 个答案:

答案 0 :(得分:2)

您可以使用函数forEach并为每个数组filter执行函数list

&#13;
&#13;
var array = [{    id: 1,    list: [{      id: 123,      name: "Dartanan"    }, {      id: 456,      name: "Athos"    }, {      id: 789,      name: "Porthos"    }]  },  {    id: 2,    list: [{      id: 111,      name: "A"    }, {      id: 222,      name: "B"    }]  }];

array.forEach(o => (o.list = o.list.filter(l => l.id != 111)));
console.log(array);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

要保持数据不可变,请使用函数map

&#13;
&#13;
var array = [{    id: 1,    list: [{      id: 123,      name: "Dartanan"    }, {      id: 456,      name: "Athos"    }, {      id: 789,      name: "Porthos"    }]  },  {    id: 2,    list: [{      id: 111,      name: "A"    }, {      id: 222,      name: "B"    }]  }],
    result = array.map(o => ({...o, list: o.list.filter(l => l.id != 111)}));

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Array.filter对元素采取行动:

var myArray = [{something: 1, list: [1,2,3]}, {something: 2, list: [3,4,5]}]

var filtered = myArray.filter(function(element) {
     return element.something === 1;
     // true = keep element, false = discard it
})

console.log(filtered); // logs [{something: 1, list: [1,2,3]}]

你可以像这样使用它:

var array = [{
    id: 1,
    list: [{
        id: 123,
        name: "Dartanan"
    }, {
        id: 456,
        name: "Athos"
    }, {
        id: 789,
        name: "Porthos"
    }]
}, {
    id: 2,
    list: [{
        id: 111,
        name: "A"
    }, {
        id: 222,
        name: "B"
    }]
}]

for (var i = 0; i < array.length; ++i) {
  var element = array[i]
  
  // Filter the list
  element.list = element.list.filter(function(listItem) {
      return listItem.id !== 111 && listItem.name !== 'A';
  })
}

console.log(array)

答案 2 :(得分:0)

您可以创建一个新数组,其中包含具有已过滤list属性的元素。

const result = array.map(element => (
  {
    ...element,
    list: element.list.filter(l => l.id !== 111)
  }
));

如果运行此代码的运行时不支持扩展运算符,则可以使用Object.assign。