首页 > 解决方案 > 如何从 Javascript 数组中删除元素?

问题描述

我想在迭代中使用带有 if 条件的 splice 方法删除数组中的某些元素。我执行以下操作:

var list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}]

list.forEach(function (item, index) {
    if (item.type == 'service'){
        list.splice(index, 1)
    }
}

//result: list = list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"}]

//expected: list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"}]

我希望将删除类型为“service”的两个元素,但只删除第一个元素。

标签: javascript

解决方案


您可以使用Array.prototype.filter()

代码:

const list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}];

const resultList = list.filter(item => item.type !== 'service');

console.log(resultList);


推荐阅读