将两个javascript对象合并为一个?

Zab*_*abs 13 javascript merge json

我试图将以下对象合并为一个但到目前为止没有运气 - 我的console.log中的结构如下:

    2018-05-11 : {posts: 2} // var posts
    2018-05-11 : {notes: 1} // var notes
Run Code Online (Sandbox Code Playgroud)

合并后,我希望它看起来像下面这样

2018-05-11 : {posts: 2, notes: 1}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过object.assign(),但它只是删除了最初的帖子数据 - 这是什么最好的方法?

Atu*_*rma 6

var x =  {posts: 2};
var y = {notes: 1};
var z = Object.assign( {}, x, y );
console.log(z);
Run Code Online (Sandbox Code Playgroud)

使用Object.assign()对象属性并将其分配给空对象.

  • 不要侮辱。事实上,OP 并没有说明日期是关键。它说这些是 _log_ 记录。你只是跳到了一个假设。我不是没有阅读问题的人。 (2认同)

And*_*one 4

这是一个更通用的函数。它通过对象传播并将合并到声明的变量中。

const posts = {  '2018-05-11': {    posts: 2  },  '2018-05-12': {    posts: 5  }};
const notes = {  '2018-05-11': {    notes: 1  },  '2018-05-12': {    notes: 3  }};

function objCombine(obj, variable) {
  for (let key of Object.keys(obj)) {
    if (!variable[key]) variable[key] = {};

    for (let innerKey of Object.keys(obj[key]))
      variable[key][innerKey] = obj[key][innerKey];
  }
}

let combined = {};
objCombine(posts, combined);
objCombine(notes, combined);
console.log(combined)
Run Code Online (Sandbox Code Playgroud)

我希望你觉得这有帮助。