javascript根据属性值从数组中删除所有对象

时间:2018-08-07 10:20:45

标签: javascript arrays ecmascript-6

如何基于属性值从数组中删除所有对象?

function removeByKey(array, fieldName){
        array.some(function(item, index) {
            return (array[index].name === fieldName) ? !!(array.splice(index, 1)) : false;
        });
        return array;
    }
    
    const myarr = [
      {
        name: 'foo',
        school: 'hoo'
      },{
        name: 'foo',
        school: 'xooo'
      },{
        name: 'bar',
        school: 'xooo'
      }
    ];
    
    console.log(removeByKey(myarr, 'foo'))

在上面的代码中,

仅删除其中一个对象。我该如何删除所有匹配项?

2 个答案:

答案 0 :(得分:2)

为什么不使用filter MDN

const myarr = [
  {
    name: 'foo',
    school: 'hoo'
  },{
    name: 'foo',
    school: 'xooo'
  },{
    name: 'bar',
    school: 'xooo'
  }
];

const filteredArray = myarr.filter(obj => obj.name !== 'foo');

示例:https://repl.it/repls/SimultaneousSentimentalForms

经过编辑以匹配注释。

答案 1 :(得分:0)

您可以为此使用过滤功能:

function removeByKey(arr, propertyValue) {

  return arr.filter(item => item.name !== propertyValue);

}

const myarr = [
  {
    name: 'foo',
    school: 'hoo'
  },{
    name: 'foo',
    school: 'xooo'
  },{
    name: 'bar',
    school: 'xooo'
  }
];

console.log(removeByKey(myarr, 'foo'));

更通用的removeByKey函数将是:

function removeByKey(arr, propertyName, propertyValue) {

  return arr.filter(item => item[propertyName] !== propertyValue);

}
const myarr = [
  {
    name: 'foo',
    school: 'hoo'
  },{
    name: 'foo',
    school: 'xooo'
  },{
    name: 'bar',
    school: 'xooo'
  }
];

console.log(removeByKey(myarr, 'name', 'foo'));