将两个javascript对象合并为一个? [英] Merging two javascript objects into one?
本文介绍了将两个javascript对象合并为一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将以下对象合并为一个,但是到目前为止还算运气不佳-其结构如下:console.log:
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 :
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}
我已经尝试过object.assign(),但是它只是删除初始帖子数据-最好的方法是什么?
I have tried object.assign() but it is just removing the initial posts data - what is the best approach for this?
推荐答案
这是一个更通用的函数.它会传播通过对象,并将合并为声明的变量.
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)
希望您对此有帮助.
这篇关于将两个javascript对象合并为一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文