对象数组格式错误

时间:2019-01-14 20:30:58

标签: javascript arrays object

不幸的是,我正在尝试格式化对象数组。

sortGroup=(group)=> {
    for (const entry of group.entries) {
     arrayofHeros.push(`Title: ${field(entry, 'Title')},'UserName': ${field(entry, 'UserName')} , Strentgh:  ${field(entry, 'Strentgh')} ,Age: ${field(entry,'Age')} \n`)   
    }
    for (const subGroup of group.groups) {
        sortGroup(subGroup)
    }
}

console.log(arrayofHeros);时的结果

 [ 'Title: Avangers: UserName: Wolvering , Strength:  Smash , Age: 28',
      'Title: X-men: UserName: Stryfe, Strength:  Superhuman, Age: 34',
      'Title: X-men: UserName: Lady Deathstrike, Strength:  Cyborg, Age: 27',
 ]

预期结果

arrayofHeros = 
[ {
    Title: 'Avangers',
    UserName: 'Wolvering',
    Strength:  'Smash',
    Age: 28
    },
    {
    Title: 'X-men',
    UserName: 'Stryfe',
    Strength:  'Superhuman',
    Age: 34
    },
    {
    Title: 'X-men',
    UserName: 'Lady Deathstrike',
    Strength:  'Cyborg',
    Age: 27,
      },
     ]

1 个答案:

答案 0 :(得分:2)

问题是您在此处输入字符串

arrayofHeros.push(`Title: ${field(entry, 'Title')},'UserName': ${field(entry, 'UserName')} , Strentgh:  ${field(entry, 'Strentgh')} ,Age: ${field(entry,'Age')} \n`)

您应该推动一个物体

arrayofHeros.push({
  Title: field(entry, 'Title'),
  UserName: field(entry, 'UserName'),
  Strentgh: field(entry, 'Strentgh'),
  Age: field(entry,'Age')
})