leblaireau
leblaireau

Reputation: 1213

Javascript - removing object from array by key value

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?

Upvotes: 3

Views: 16474

Answers (4)

nurhamsah
nurhamsah

Reputation: 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);

Upvotes: 0

hairmot
hairmot

Reputation: 2975

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);
}

Upvotes: 4

Rishikesh Dhokare
Rishikesh Dhokare

Reputation: 3589

  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);

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122027

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)

Upvotes: 13

Related Questions