a6rnaw
Last Updated: November 03, 2016
·
25.2K
· jabclab
4f4bf0fbd4cc6de6159d78f9f9fb3aa6

Native object copy in Node.js

In order to shallow clone an Object in Node.js we can use the following method from util:

var extend = require('util')._extend;

var original = { foo: 'bar' };
var extended = extend(original, { another: 'attribute' }); 
// { foo: 'bar', another: 'attribute' }

This _extend function can be found in the Node.js source here.

I discovered this via this StackOverflow answer.

Say Thanks
Respond

3 Responses
Add your response

17163
None

Now Node.js source is https://github.com/joyent/node/blob/master/lib/util.js#L640
It changes over time just because node.js source code changes as well :)

over 1 year ago ·
21354
Default profile 6 normal

You have to bear in mind your node.js version. If you're running Azure Mobile Services for example, you won't have the _extend util. Here are the docs: http://nodejs.org/docs/v0.8.28/api/util.html

over 1 year ago ·
28272

As mentionned on https://nodejs.org/docs/latest/api/util.html#util_util_extend_target_source

The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.

=> use Object.assign

over 1 year ago ·