我需要将我的对象转换为对象数组 我的对象在下面:
[
{name: 'Superman'},
{realName: 'Clark Kent'},
{height: 75},
{weight: 235},
{hero: true},
{villain: false},
{allies: [superHero: 'Batman',
superPower: 'He is rich',
sidekick: 'robin']}
]
&我需要将其转换为:
{{1}}
答案 0 :(得分:2)
请尝试
var superman = {
name: 'Superman',
'real name': 'Clark Kent',
height: 75,
weight: 235,
hero: true,
villain: false,
allies: {superHero: 'Batman',
superPower: 'He is rich',
sidekick: 'robin'}
};
var ret = Object.keys(superman).map(function(key) {
return { [key]: superman[key] };
});
console.log(ret);
答案 1 :(得分:0)
如果要将主对象中的每个对象修改为您描述的结构(递归),请使用以下方法:
var superman = {
name: 'Superman',
'real name': 'Clark Kent',
height: 75,
weight: 235,
hero: true,
villain: false,
allies: {
superHero: 'Batman',
superPower: 'He is rich',
sidekick: 'robin'
}
};
const toArray = (obj) => {
return Object.entries(obj).map(([key, value]) => {
const ret = {}
if (typeof value === 'object' && Object.keys(value).length) {
ret[key] = toArray(value)
} else {
ret[key] = value
}
return ret
})
}
console.log(toArray(superman))