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
so it seems I need an index or maybe there is a better ES6 way?
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?
Share Improve this question edited Aug 7, 2018 at 10:49 hairmot 2,9751 gold badge15 silver badges26 bronze badges asked Aug 7, 2018 at 10:17 leblaireauleblaireau 1,2134 gold badges11 silver badges13 bronze badges 2 |4 Answers
Reset to default 13You 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)
To remove bob simply do the opposite equality check
let person = people.filter(person => person.Name !== 'Bob')
To mutate the original array, you can use splice
const index = people.findIndex(person => person.Name === 'Bob');
if (index > -1) {
people.splice(index, 1);
}
- Find the index of the object where
name = "Bob"
- Remove it from the array using
splice()
people.splice(people.findIndex(({Name}) => Name == "Bob"), 1);
Just simply change your code in the filter section from "===" to "!==" to delete it.
let people = [
{
Name: "Bob",
Age: "45",
},
{
Name: "Jim",
Age: "45",
},
];
let person = people.filter((person) => person.Name !== "Bob");
console.log(person);
splice()
?? – Muhammad Usman Commented Aug 7, 2018 at 10:19let person = people.filter(person => person.Name!== 'Bob')
. Filter will only return elements that return false to your condition and ignore the others. – Nathan Stockton Commented Aug 7, 2018 at 10:23