Reputation: 91
I have two objects something like this and need to combine them and create an array.
var firstData = {
label: "Out",
data: [
{
value: 2,
title: "20-06-18 09:00",
},
{
value: 5,
title: "20-06-18 08:00",
}
]
}
var secondData = {
label: "In",
data: [
{
value: 4,
title: "20-06-18 09:00",
},
{
value: 8,
title: "20-06-18 08:00",
}
]
}
The result Should be an array like this an array of object where you combine the title with labels "In" and "Out".
var result =
[
{
title: "20-06-18 09:00",
data: [
{
value: 4,
label: "In",
},
{
value: 2,
label: "Out",
}
]
},
{
title: "20-06-18 08:00",
data: [
{
value: 8,
label: "In",
},
{
value: 5,
label: "Out",
}
]
},
]
Can anyone help, please? I will try to post a fiddler example soon. Thanks in advance.
Upvotes: 0
Views: 48
Reputation: 5318
You can make use of reduce
to achieve your task:
var firstData = { label: "Out", data: [ { value: 2, title: "20-06-18 09:00", }, { value: 5, title: "20-06-18 08:00", } ] };
var secondData = { label: "In", data: [ { value: 4, title: "20-06-18 09:00", }, { value: 8, title: "20-06-18 08:00", } ] };
var result = Object.values([firstData, secondData].reduce((acc,elem)=>{
elem.data.forEach(({value, title})=>{
acc[title] = acc[title] || {title, data:[]};
acc[title].data.push({value, label:elem.label});
});
return acc;
},{}));
console.log(result);
Upvotes: 2