我需要将对象转换为对象数组

我需要将我的对象转换为对象数组我的对象如下:


superman = {

    name: 'Superman',

    'real name': 'Clark Kent',

    height: 75,

    weight: 235,

    hero: true,

    villain: false,

    allies: {superHero: 'Batman',

             superPower: 'He is rich',

             sidekick: 'robin'}

    }

&我需要它转换成:


[

    {name: 'Superman'},

    {realName: 'Clark Kent'},

    {height: 75},

    {weight: 235},

    {hero: true},

    {villain: false},

    {allies: [superHero: 'Batman',

             superPower: 'He is rich',

             sidekick: 'robin']}

]


哔哔one
浏览 167回答 2
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);

FFIVE

如果要将主对象中的每个对象修改为您描述的结构(递归),请使用以下命令: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))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript