最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - removing object from array by key value - Stack Overflow

programmeradmin2浏览0评论

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
  • you wanna remove an element from array ? splice() ?? – Muhammad Usman Commented Aug 7, 2018 at 10:19
  • 2 just flip it around - let 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
Add a comment  | 

4 Answers 4

Reset to default 13

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)

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

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

发布评论

评论列表(0)

  1. 暂无评论