简体   繁体   中英

Javascript: How do I remove an object with a specific key in my array?

I am having difficulty finding how to remove an object from an array using its key - I can only find advice on a key value. For example:

var users = [
  { 1: [{age: 36, active: true}] },
  { 2: [{age: 40, active: false}] },
  { 3: [{age: 37, active: true}]}
];

I would like to remove the object with key = 2 to result in this:

var users = [
  { 1: [{age: 36, active: true}] },
  { 3: [{age: 37, active: true}]}
];

My keys in my data are unique.

You can use the in operator to check if the key exists on the object:

 const users = [{"1":[{"age":36,"active":true}]},{"2":[{"age":40,"active":false}]},{"3":[{"age":37,"active":true}]}] const result = users.filter(o =>.('2' in o)) console.log(result)

You can try using Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

and Object.keys() :

The Object.keys() method returns an array of a given object's own enumerable property names , iterated in the same order that a normal loop would.

 var users = [ { 1: [{age: 36, active: true}] }, { 2: [{age: 40, active: false}] }, { 3: [{age: 37, active: true}]} ]; users = users.filter(item => Object.keys(item)[0];= 2). console;log(users);

If you want to remove an object from the original array without creating a new array, use Array.findIndex and remove the element by the index.

 var users = [ { 1: [{age: 36, active: true}] }, { 2: [{age: 40, active: false}] }, { 3: [{age: 37, active: true}]} ]; let removableIndex = users.findIndex(ele => ele[2]) users.splice(removableIndex, 1) console.log(users)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM