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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50176456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:57:53  来源:igfitidea点击:

Merging two javascript objects into one?

javascriptjsonmerge

提问by Zabs

I am trying to merge the following objects into one but having no luck so far - the structure is as follows in my console.log :

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

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

Once merged I want it to look like the following

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

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

I have tried object.assign() but it is just removing the initial posts data - what is the best approach for this?

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

采纳答案by Andrew Bone

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)

I hope you find this helpful.

我希望你觉得这有帮助。

回答by Atul Sharma

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

Use Object.assign()and assign object properties to empty object.

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

回答by MayK

you need to apply assign to each item like this:

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

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);

回答by Mamun

You can do the following with Object.assign():

您可以执行以下操作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);

回答by Nenad Vracar

You could use mergemethod from Lodash library.

您可以使用mergeLodash 库中的方法。

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>

回答by M Ciel

jQuery.extend()might help. Try

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

$.extend(obj1, obj2)