我有多个类似的 JSON
var object1 = {name: "John"};
var object2 = {location: "San Jose"};
它们不是嵌套或类似的东西。只是基本上不同的领域。我需要在 node.js 中将它们组合成一个 JSON
,如下所示:
{name: "John", location: "San Jose"}
我可以使用 jQuery 就好了。这是浏览器中的一个工作示例:
http://jsfiddle.net/qhoc/agp54/
但如果我在 node.js 中执行此操作,我不想加载 jQuery(这有点过度使用,加上 node.js' jQuery 不会不能在我的 Windows 机器上工作)。
那么有没有一种简单的方法来做类似于 $.extend()
而没有 jQuery 的事情?
最佳答案
对于这样一个简单的浅层合并用例,无需重新发明轮子。
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed
console.log(obj === o1) // true
即使是来自 Node.js say so 的人:
_extend
was never intended to be used outside of internal NodeJS modules. The community found and used it anyway. It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality throughObject.assign
.
自从 version 8.6 , 可以原生使用 spread operator在 Node.js 中。示例如下:
let o1 = { a: 1 };
let o2 = { b: 2 };
let obj = { ...o1, ...o2 }; // { a: 1, b: 2 }
Object.assign
仍然有效。
https://stackoverflow.com/questions/14974864/