问题
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:
- Find the index of the object where
name = "Bob"
- 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