I have object of array of object. How to convert array of objects to array of arrays?
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 },
]
}
]
I tried use 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]
And get the results
dataConvert = [
["2020-7", "2020-8"],
[1234, 3445, 3333, 4444]
]
I want the output looks like this:
output = [
["2020-7", "2020-8"],
["p1", 1234, 3333],
["p2", 3445, 4444],
]
Please help me.
-
Could you please show us some code you have tried so far?Harmandeep Singh Kalsi– Harmandeep Singh Kalsi2020年08月11日 07:53:02 +00:00Commented Aug 11, 2020 at 7:53
-
You need to show your code and describe what was the problem. Please read How to Ask and how to create minimal reproducible example.Yury Tarabanko– Yury Tarabanko2020年08月11日 07:53:26 +00:00Commented Aug 11, 2020 at 7:53
-
@HarmandeepSinghKalsi I have edited the articleminhminh– minhminh2020年08月11日 08:24:42 +00:00Commented Aug 11, 2020 at 8:24
2 Answers 2
Try like below. Explanation is in comment.
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);
answered Aug 11, 2020 at 8:37
Karan
12.7k3 gold badges31 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Krzysztof Kaczyński
@minhminh this is not the same structure because time elements are not inside an array. Please check my example
This should work for you:
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);
answered Aug 11, 2020 at 8:35
Krzysztof Kaczyński
5,1516 gold badges36 silver badges62 bronze badges
Comments
lang-js