我有对象数组的对象。如何将对象数组转换为数组?
input = [
{
time: "2020-7",
tasks: [
{code: "p1", value: 1234},
{ code: "p2", value: 3445 },
]
},
{
time: "2020-8",
tasks: [
{ code: "p1", value: 3333 },
{ code: "p2", value: 4444 },
]
}
]我试过使用forEach
let dataConvert=[], date=[],data=[];
input.forEach(x=>{
return date = [...date, x.time]
})
console.log(date)
input.forEach(x=>{
x.tasks.forEach(y=>{
data = [...data,y.value]
})
})
console.log(data);
dataConvert= [...dataConvert,date,data]并得到结果
dataConvert = [
["2020-7", "2020-8"],
[1234, 3445, 3333, 4444]
]我要输出如下所示:
output = [
["2020-7", "2020-8"],
["p1", 1234, 3333],
["p2", 3445, 4444],
]请帮帮我。
发布于 2020-08-11 08:37:10
试试下面的样子。解释在评论中。
let input = [
{
time: "2020-7",
tasks: [
{code: "p1", value: 1234},
{ code: "p2", value: 3445 },
]
},
{
time: "2020-8",
tasks: [
{ code: "p1", value: 3333 },
{ code: "p2", value: 4444 },
]
}
];
// get array of time values.
let output = input.map(x => x.time);
// flatMap will create 1d array of tasks
// reduce will return object with key as code and value as an array of values for respective tasks.
let values = Object.values(input.flatMap(x => x.tasks).reduce((a, i) => {
a[i.code] = a[i.code] || [i.code];
a[i.code].push(i.value);
return a;
}, {}));
// use spread operator to combine both values.
output = [output, ...values];
console.log(output);
发布于 2020-08-11 08:35:20
这应该适用于你:
const input = [{
time: "2020-7",
tasks: [{
code: "p1",
value: 1234
},
{
code: "p2",
value: 3445
},
]
},
{
time: "2020-8",
tasks: [{
code: "p1",
value: 3333
},
{
code: "p2",
value: 4444
},
]
}
];
const time = [];
const tasks = new Map();
for (const elem of input) {
time.push(elem.time);
for (const task of elem.tasks) {
if (tasks.has(task.code)) {
tasks.get(task.code).push(task.value.toString())
} else {
tasks.set(task.code, [task.value.toString()]);
}
}
}
const result = [time];
for (const [key, value] of tasks.entries()) {
result.push([key, ...value]);
}
console.log(result);
https://stackoverflow.com/questions/63353798
复制相似问题