具有嵌套对象的多个对象的展平数组
Posted
技术标签:
【中文标题】具有嵌套对象的多个对象的展平数组【英文标题】:Flatten array with multiple objects with nested objects 【发布时间】:2021-01-14 08:28:18 【问题描述】:我正在尝试做的这个特别理想的结果是比我对刚开始编程的人所期望的更具挑战性。
我将 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 所以希望能得到一些指示
谢谢!
【问题讨论】:
你认为你为什么需要.flatMap()
?要么使用.map()
并构建全新的对象,要么使用.forEach()
并修改现有对象(添加balance
、level
、删除playerInfo
)
【参考方案1】:
您可以使用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));
【讨论】:
很高兴能帮上忙 :)【参考方案2】:您可以直接使用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);
【讨论】:
【参考方案3】:简短而甜蜜的是:
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)
【讨论】:
以上是关于具有嵌套对象的多个对象的展平数组的主要内容,如果未能解决你的问题,请参考以下文章
将嵌套的 JSON 对象展平并排序到 javascript 中的数组中