我有嵌套的数组格式,其中没有名称分配给值,格式如下所示:
response.data: [{
2018: [{
December: [{
complaintRaised: 8
totalClosed: 0
totalPending: 8
totalResolved: 0
}]
}],
2019: [{
January: [{
complaintRaised: 2
totalClosed: 0
totalPending: 2
totalResolved: 0
}]
}]
}]
我需要将其转换为单个数组,并将键名分配给这些值。
response.data: [{
key: "2019"
complaintRaised: 8
totalClosed: 0
totalPending: 8
totalResolved: 0
year: "2018-December"
},
{
key: "2018"
complaintRaised: 2
totalClosed: 0
totalPending: 2
totalResolved: 0
year: "2019-January"
}
]
答案 0 :(得分:1)
如果要将第一个数组中的对象键映射为每个扁平化元素的属性,请使用纯JavaScript来使用下面的代码。
请告诉我是否可以解决您的问题。
const x = [{
2018: [{
December: [{
complaintRaised: 8,
totalClosed: 0,
totalPending: 8,
totalResolved: 0
}]
}],
2019: [{
January: [{
complaintRaised: 2,
totalClosed: 0,
totalPending: 2,
totalResolved: 0
}]
}]
}];
const result = Object.entries(x[0]).map((e) => {
return Object.assign(
{},
Object.values(e[1][0])[0][0],
{ key: e[0], year: e[0] + '-' + Object.keys(e[1][0])[0] }
);
})
console.log(result);