简体   繁体   中英

How to insert key,value pair of object to an array?

i have an object like this:

var obj = {
   0: {...},
   1: {...},
   2: {...}, 
   3: {...},
   4: {...}
}

And then i have an if statement with some logic to see wich values i want in each key. If found some values i want to insert that into an array but with the same key/value as the object, like this:

var array = [ 1: {...}, 3: {...}, 4:{...} ];

My problem is when i am creating the array and inserting the values and when i see in development tools in chrome for exemplo the console it stays always like this:

var array = [ 0: {...}, 1: {...}, 2:{...} ];

Even if the values are what i want the keys always start with 0. I am just doing an 'if' and then push that into my array.

for (const [key, value] of Object.entries(obj)) {
  if(key == obj.someValue){
      arr.push(value);   
   }
}

This is my logic. Someone can help me?

Array push() will create sequentially numbered keys. If there is a need for having the same key into the new array you can use

if(key == obj.someValue){
   arr[key] = value;   
}

To retrieve both key and value from new array, use for-in

for (key in arr) {
   console.log(key); //key
   console.log(arr[key]); //value
}

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