I have multiple JSON
like those
var object1 = {name: "John"}; var object2 = {location: "San Jose"};
They are not nesting or anything like that. Just basically different fields. I need to combine them into one single JSON
in node.js like this:
{name: "John", location: "San Jose"}
I can use jQuery just fine. Here is a working example in the browser:
http://jsfiddle.net/qhoc/agp54/
But if I do this in node.js, I don't want to load jQuery (which is a bit over use, plus node.js' jQuery doesn't work on my Windows machine).
So is there a simple way to do things similar to $.extend()
without jQuery?
Merging objects in JavaScript is possible in different ways. Two common approaches are Object. assign() or the … spread operator.
JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.
jQuery is just a javascript library. NodeJS is a server side development platform, so that you can run javascript on a server. jQuery runs in NodeJS, but there would never be a need to "run" NodeJS on the clientside, because NodeJS just allows javascript to run on a server.
There's no need to reinvent the wheel for such a simple use case of shallow merging.
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
Even the folks from 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
.
Since version 8.6, it's possible to natively use the spread operator in Node.js. Example below:
let o1 = { a: 1 }; let o2 = { b: 2 }; let obj = { ...o1, ...o2 }; // { a: 1, b: 2 }
Object.assign
still works, though.
PS1: If you are actually interested in deep merging (in which internal object data -- in any depth -- is recursively merged), you can use packages like deepmerge, assign-deep or lodash.merge, which are pretty small and simple to use.
PS2: Keep in mind that Object.assign doesn't work with 0.X versions of Node.js. If you are working with one of those versions (you really shouldn't by now), you could use require("util")._extend
as shown in the Node.js link above -- for more details, check tobymackenzie's answer to this same question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With