Javascript - removing object from array by key value

前端 未结 4 1467
清歌不尽
清歌不尽 2020-12-20 02:29

I have an array of objects

let people = [{

  Name: \'Bob\',

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

  Age: \'45\',
}

];

let person = people.filter(person =         


        
相关标签:
4条回答
  • 2020-12-20 03:01

    You can use filter like this

    people = people.filter(function( obj ) {
    return obj.Name !== 'Bob';});
    
    0 讨论(0)
  • 2020-12-20 03:02
    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);

    0 讨论(0)
  • 2020-12-20 03:10

    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);
    }
    
    0 讨论(0)
  • 2020-12-20 03:12

    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)

    0 讨论(0)
提交回复
热议问题