[英]Merge two objects into array in JavaScript
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".结果应该是一个像这样的数组 object 的数组,您将标题与标签“In”和“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.提前致谢。
You can make use of reduce
to achieve your task:您可以使用reduce
来完成您的任务:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.