将两个JavaScript对象合并成一个?

这个问题在这里已经有了答案:

  • 我如何动态合并两个JavaScript对象的属性? 55个答案

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

    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)

    另一种方法是使用可在支持ES6或ES2015的浏览器上使用的扩展语法

    const posts = {'2018-05-11' : {posts: 2}}
    const notes = {'2018-05-11' : {notes: 1}}
    
    let result = { ...posts , ...notes }
    

    var x =  {posts: 2};
    var y = {notes: 1};
    var z = Object.assign( {}, x, y );
    console.log(z);
    链接地址: http://www.djcxy.com/p/27337.html

    上一篇: Merging two javascript objects into one?

    下一篇: Javascript union of two object