Zab*_*abs 13 javascript merge json
我试图将以下对象合并为一个但到目前为止没有运气 - 我的console.log中的结构如下:
2018-05-11 : {posts: 2} // var posts
2018-05-11 : {notes: 1} // var notes
Run Code Online (Sandbox Code Playgroud)
合并后,我希望它看起来像下面这样
2018-05-11 : {posts: 2, notes: 1}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过object.assign(),但它只是删除了最初的帖子数据 - 这是什么最好的方法?
var x = {posts: 2};
var y = {notes: 1};
var z = Object.assign( {}, x, y );
console.log(z);Run Code Online (Sandbox Code Playgroud)
使用Object.assign()对象属性并将其分配给空对象.
这是一个更通用的函数。它通过对象传播并将合并到声明的变量中。
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)Run Code Online (Sandbox Code Playgroud)
我希望你觉得这有帮助。
| 归档时间: |
|
| 查看次数: |
13343 次 |
| 最近记录: |