使用嵌套对象展平包含多个对象的数组

我试图做的这个特别期望的结果结果证明比我对刚开始编程的人所期望的更具挑战性。


我将 API 查询的结果存储在如下所示的数组变量中:


[{

  balance: 4444,

  playerInfo: {

    age: "18",

    gender: "Male",

    level: "2",

    name: "Joe"

  }

}, {

  balance: 3333,

  playerInfo: {

    age: "45",

    gender: "Male",

    level: "3",

    name: "Angel"

  }

}, {

  balance: 2222,

  playerInfo: {

    age: "20",

    gender: "Female",

    level: "11",

    name: "Luce"

  }

}]

我想要的结果是:


[{

  balance: 4444,

  level: "2",

  name: "Joe"

}, {

  balance: 3333,

  level: "3",

  name: "Angel"

}, {

  balance: 2222,

  level: "11",

  name: "Luce"

}]

我在 flat 和 flatMap 方面取得了一些小进展,但不完全确定它是否是实现兼容性的正确方法,因为预期的目标群体可能正在使用过时的浏览器。


其他一些答案的逻辑对我来说有点难以理解 atm 所以希望能提供一些建议以防万一


慕村225694
浏览 126回答 3
3回答

饮歌长啸

您可以使用Array.map和Object destructuring。let data = [{balance:4444,playerInfo:{age:"18",gender:"Male",level:"2",name:"Joe"}},{balance:3333,playerInfo:{age:"45",gender:"Male",level:"3",name:"Angel"}},{balance:2222,playerInfo:{age:"20",gender:"Female",level:"11",name:"Luce"}}]const formatData = (data) => {  return data.map(({balance, playerInfo}) => ({    balance,    level: playerInfo.level,    name: playerInfo.name  }))}console.log(formatData(data))let data = [{balance:4444,playerInfo:{age:"18",gender:"Male",level:"2",name:"Joe"}},{balance:3333,playerInfo:{age:"45",gender:"Male",level:"3",name:"Angel"}},{balance:2222,playerInfo:{age:"20",gender:"Female",level:"11",name:"Luce"}}]const formatData = (data) => {  return data.map(({ balance, playerInfo: { level, name }}) => ({    balance,    level,    name  }))}console.log(formatData(data));

白衣非少年

简短的'n甜蜜是这样的:let rawData = [{  balance: 4444,  playerInfo: {    age: "18",    gender: "Male",    level: "2",    name: "Joe"  }}, {  balance: 3333,  playerInfo: {    age: "45",    gender: "Male",    level: "3",    name: "Angel"  }}, {  balance: 2222,  playerInfo: {    age: "20",    gender: "Female",    level: "11",    name: "Luce"  }}]let formattedData =  rawData.map(({    balance,    playerInfo: {      level,      name    }  }) => ({ balance, level, name }))console.log(formattedData)

跃然一笑

您可以直接使用map方法进行转换。let input = [{  balance: 4444,  playerInfo: {    age: "18",    gender: "Male",    level: "2",    name: "Joe"  }}, {  balance: 3333,  playerInfo: {    age: "45",    gender: "Male",    level: "3",    name: "Angel"  }}, {  balance: 2222,  playerInfo: {    age: "20",    gender: "Female",    level: "11",    name: "Luce"  }}];let output = input.map(obj => ({  balance: obj.balance,  level: obj.playerInfo?.level,  name: obj.playerInfo?.name,}));console.log(output);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript