Is there a pure functional equivalent to goog.object.extend?

Per Closing Documentation :

Extends an object with another object. It acts "in place"; it does not create a new object. Example: var o = {}; goog.object.extend (o, {a: 0, b: 1}); about; // {a: 0, b: 1} goog.object.extend (o, {b: 2, c: 3}); about; // {a: 0, b: 2, c: 3}

But this is not a functional approach, and for many contexts a functional approach is better. Does Closure offer something more modern for this?

eg.

goog.object.extend(a, b);

becomes

a = goog.object.extend(a, b);
+2
source share
2 answers

You can create a new object using an empty object literal, which will be expanded with the objects you want to copy-merge:

var x = {};
goog.object.extend(x, a, b);
a = x;

, Object.create(Object.getPrototypeOf(a)).

+4

:

var a = {};
var b = extend(a, { a: 0, b: 1 });
var c = extend(b, { b: 2, c: 3 });

console.log(a, b, c);

function extend(a, b) {
    var result = {};
    for (var x in a) if (a.hasOwnProperty(x)) result[x] = a[x];
    for (var x in b) if (b.hasOwnProperty(x)) result[x] = b[x];
    return result;
}
Hide result

, .

0

Source: https://habr.com/ru/post/1691158/


All Articles