我需要将对象的每个对象移到数组中。 我的对象如下图
obj = { obj1: {}, obj2: {}, obj3: {}}
我需要将每个对象都转换为数组,并且它应该如下图所示
array[0] = obj1
array[1] = obj2
array[2] = obj3
有人可以帮我吗?
答案 0 :(得分:1)
const obj = {obj1: {foo: 'bar'}, obj2: {foo: 'baz'}}
const result = Object.values(obj)
console.log(result)
答案 1 :(得分:1)
来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
Object.values()方法返回给定对象自己的可枚举属性值的数组,其顺序与for ... in循环所提供的顺序相同(区别在于for-in循环枚举了in ...原型链)。
const input = { obj1: {}, obj2: {}, obj3: {}};
console.log(Object.values(input));
(3)[{…},{…},{…}]
0:{}
1:{}
2:{}
长度:3
答案 2 :(得分:1)
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)
答案 3 :(得分:0)
就这么简单
let obj = { obj1: {}, obj2: {}, obj3: {}}
console.log(Object.keys(obj).map(k => obj[k]))
答案 4 :(得分:0)
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);