Javascript - removing object from array by key value

一曲冷凌霜 提交于 2020-06-17 07:02:20

问题


I have an array of objects

let people = [{

  Name: 'Bob',

  Age: '45',
},
{
  Name: 'Jim',

  Age: '45',
}

];

let person = people.filter(person => person.Name=== 'Bob') 

This returns Bob but how do I delete him?

This only seems to delete a property

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

so it seems I need an index or maybe there is a better ES6 way?


回答1:


You can use splice and findIndex methods and remove specific object from an array.

let people = [{"Name":"Bob","Age":"45"},{"Name":"Jim","Age":"45"}]

people.splice(people.findIndex(({Name}) => Name == "Bob"), 1);
console.log(people)



回答2:


To remove bob simply do the opposite equality check

let person = people.filter(person => person.Name !== 'Bob') 



回答3:


  1. Find the index of the object where name = "Bob"
  2. Remove it from the array using splice()

people.splice(people.findIndex(({Name}) => Name == "Bob"), 1);




回答4:


You can use filter like this

people = people.filter(function( obj ) {
return obj.Name !== 'Bob';});


来源:https://stackoverflow.com/questions/51724323/javascript-removing-object-from-array-by-key-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!