Merging two javascript objects into one?

This question already has an answer here:

  • How can I merge properties of two JavaScript objects dynamically? 55 answers

  • Here's a function that's a bit more generic. It propagates through the object and will merge into a declared variable.

    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/27338.html

    上一篇: JSON复制到JSON基于密钥复制

    下一篇: 将两个JavaScript对象合并成一个?