我尝试将以下对象合并为一个对象,但迄今为止没有成功-在我的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(),但它只是删除了初始帖子数据 - 有什么更好的方法吗?
我尝试将以下对象合并为一个对象,但迄今为止没有成功-在我的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(),但它只是删除了初始帖子数据 - 有什么更好的方法吗?
var x = {posts: 2};
var y = {notes: 1};
var z = Object.assign( {}, x, y );
console.log(z);
Object.assign()
将对象属性分配给空对象。2018-05-11
键。 - WanciehoYou can do the following with 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);
这里有一个更通用的函数。它会遍历整个对象并将内容合并到已声明的变量中。
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)
希望这对您有所帮助。
objCombine(obj [key],variable [key])
替换以for(let innerkey ...
开头的两行。我认为-没有测试过。 - ToolmakerStevemerge
方法。
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>
merge
可能是值得的。 - Auspexvar 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);
jQuery.extend() 可能会有帮助。
默认情况下,$.extend() 执行的合并不是递归的;如果第一个对象的属性本身就是一个对象或数组,则它将被第二个或后续对象中具有相同键的属性完全覆盖。值不会合并。但是,通过为第一个函数参数传递 true,对象将递归合并。
试试
$.extend(obj1, obj2)
Object.assign( a, b )
。如果你想将 a 和 b 都添加到一个新对象中,请使用Object.assign( {}, a, b )
。你能展示一下你尝试过的Object.assign()
代码吗? - Shillykeys
是唯一的。像这样循环遍历它非常容易。 - deEr.