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

Flatten array with multiple objects with nested objects

事实证明,我想要实现的这个特别理想的结果比我对刚开始编程的人的预期更具挑战性。

我将 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 所以希望能得到一些建议以防万一

谢谢!

您可以使用 Array.mapObject 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));

可以直接使用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);

简短而甜蜜的是:

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)