简体   繁体   English

如何将对象的键值对插入数组?

[英]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 语句来查看每个键中我想要的值。 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:我的问题是当我创建数组并插入值时,当我在 chrome 中的开发工具中看到控制台时,它总是这样:

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.即使值是我想要的,键总是从 0 开始。我只是在做一个“如果”,然后将它推入我的数组。

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.数组 push() 将创建按顺序编号的键。 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-in

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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