我正在尝试基于ES6中一周的同一天合并和排列嵌套对象?如何添加新对象?
见下面的例子:
let opens = {name:"Fri", series: [name: "opens", value: 24]}
let clicks= {name:"Fri", series: [name: "clicks", value: 22]}
let sent= {name:"Fri", series: [name: "sent", value: 22]}
Into {name:"Fri", series: [{name: "opens", value: 24},{name: "opens", value: 24},{[name: "sent", value: 22]}]}
答案 0 :(得分:0)
问题不明确。您无法以这种方式定义三个对象。结果包含两个名称打开的元素,这可能是另一个错误。
答案 1 :(得分:0)
假设有效对象,即:
{name:"Fri", series: {name: "opens", value: 24}}
您可以将三个对象放入一个数组中,然后执行函数reduce
。
let opens = {name:"Fri", series: {name: "opens", value: 24}};
let clicks= {name:"Fri", series: {name: "clicks", value: 22}};
let sent= {name:"Fri", series: {name: "sent", value: 22}};
var result = Object.values([opens, clicks, sent].reduce((a, c) => {
(a[c.name] || (a[c.name] = {name: c.name, series: []})).series.push(c.series);
return a;
}, {}));
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }