简体   繁体   English

如何读取对象内部的每个对象并移至数组

[英]How to read each object inside object and move to array

I have a requirement to move each object of object into array. 我需要将对象的每个对象移动到数组中。 My object looks like below 我的对象如下所示

obj = { obj1: {}, obj2: {}, obj3: {}}

I need to convert each object into array and it should look like below 我需要将每个对象转换为数组,并且应该如下所示

array[0] = obj1
array[1] = obj2
array[2] = obj3

Can someone please help me? 有人可以帮帮我吗?

Use Object.values : 使用Object.values

 const obj = {obj1: {foo: 'bar'}, obj2: {foo: 'baz'}} const result = Object.values(obj) console.log(result) 

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values 来自https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/values

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). Object.values()方法返回给定对象自己的可枚举属性值的数组,其顺序与for ... in循环提供的顺序相同(不同之处在于,for-in循环枚举原型链中的属性以及)。

const input = { obj1: {}, obj2: {}, obj3: {}};
console.log(Object.values(input));

(3) [{…}, {…}, {…}] (3)[{…},{…},{…}]

0: {} 0:{}

1: {} 1:{}

2: {} 2:{}

length: 3 长度:3

3 different methods 3种不同的方法

 const obj = { obj: { name: 'obj1' }, obj2: { name: 'obj2' }, obj3: { name: 'obj3' }} // option 1 const arr = [] for (let key in obj) arr.push(obj[key]) // option 2 const arr2 = Object.keys(obj).map(key => obj[key]) // option 3 const arr3 = Object.values(obj) console.log(arr) console.log(arr2) console.log(arr3) 

Simple as this 就这么简单

let obj = { obj1: {}, obj2: {}, obj3: {}}
console.log(Object.keys(obj).map(k => obj[k]))
const obj = {obj1: {foo: 'bar',foo1: 'bar1'}, obj2: {foo: 'baz'}}

var keyObj = Object.keys(obj);
var valueObj = Object.values(obj);
const newObj = [];
for(let i = 0;i < keyObj.length;i++) {
  var tmp = [];
  tmp[keyObj[i]] = valueObj[i]; 
  newObj.push(tmp);
}
console.log(newObj);

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

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