Lunari
Lunari

Reputation: 11

How can I get index of prop in object?

I have an object in Vue and it looks like this:

list {
123456 : Array [2]
223456 : Array [5]
323456 : Array [8]
423456 : Array [0]
523456 : Array [1]
623456 : Array [3]
}

Now I want to delete the one with array 0 so 423456 (it is numeric not a string). How can I get it?

Upvotes: 0

Views: 77

Answers (3)

N. Ivanov
N. Ivanov

Reputation: 1823

You just have to specify the key to delete

Here is a working example.

var list = {
  123456: Array[2],
  223456: Array[5],
  323456: Array[8],
  423456: Array[0],
  523456: Array[1],
  623456: Array[3]
};

var toBeDeleted = 423456;

delete list[toBeDeleted];

console.log(list);

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68433

Use reduce to assign the list without empty array

list = Object.keys(list).reduce( (acc, c) => {
   if ( list[c].length > 0 ) 
   {
     acc[c] = list[c];
   }
}, {});

Demo

var list = {
  123456: [1, 2],
  223456: [1, 2, 3],
  323456: [1, 2, 4, 5],
  423456: [],
  523456: [1, 2],
  623456: [1, 2, 4, 5]
};

list = Object.keys(list).reduce((acc, c) => {
  if (list[c].length > 0) {
    acc[c] = list[c];
  }
  return acc;
}, {});

console.log(list);

Upvotes: 0

31piy
31piy

Reputation: 23869

You can loop through the object's keys and find the empty values first. Then loop again to delete those keys:

let list = {
  123456: [1, 2],
  223456: [1, 2, 3, 4, 5],
  323456: [1, 2, 3, 4, 5, 6, 7, 8],
  423456: [],
  523456: [1],
  623456: [1, 2, 3]
};

Object.keys(list)
  .filter(key => list[key].length === 0)
  .forEach(key => {
    delete list[key];
  });

console.log(list);

Upvotes: 1

Related Questions