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

时间:2018-05-04 13:46:44

标签: javascript json merge

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

    2018-05-11 : {posts: 2} // var posts
    2018-05-11 : {notes: 1} // var notes

合并后,我希望它看起来像以下

2018-05-11 : {posts: 2, notes: 1}

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

6 个答案:

答案 0 :(得分:5)



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




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

答案 1 :(得分:2)

您需要对每个项目应用分配:



var a =  {"2018-05-11" : {notes: 1}};

var b =  {"2018-05-11" : {posts: 3}};

var result = {};

Object.keys(a).forEach(k=>{result[k] = Object.assign(a[k],b[k])});

console.log(result);




答案 2 :(得分:2)

这是一个更通用的功能。它通过对象传播,并将合并为声明的变量。

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)

我希望你觉得这很有用。

答案 3 :(得分:1)

您可以使用Lodash库中的merge方法。



const posts = {'2018-05-11' : {posts: 2}}
const notes = {'2018-05-11' : {notes: 1}}

const result = _.merge({}, posts, notes);
console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
&#13;
&#13;
&#13;

答案 4 :(得分:1)

jQuery.extend()可能有所帮助。尝试

$.extend(obj1, obj2)

答案 5 :(得分:1)

您可以使用Object.assign()执行以下操作:

var posts = {'2018-05-11' : {posts: 2}} // var posts
var notes = {'2018-05-11' : {notes: 1}} // var notes

Object.assign(posts['2018-05-11'], notes['2018-05-11']);
console.log(posts);

相关问题