Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying properties from one object to another with a condition

Lazy-me is wondering if there a better way to copy the properties in one object (source) over to another object (destination) only if the properties exist in the latter? It does not necessarily have to be using Underscore.

For example,

_.mixin({
    assign: function (o, destination, source) {
        for (var property in source) {
            if (destination.hasOwnProperty(property)) {
                destination[property] = source[property];
            }
        }
        return destination;
    }
});

console.log( _().assign({ a: 1, b: 2, d: 3 }, { a: 4, c: 5 }) ) // a: 4, b: 2, d: 3
like image 640
Mikey Avatar asked Aug 15 '16 10:08

Mikey


People also ask

How do you copy properties from one object to another?

assign is the standard way to copy properties from one object to another. It is often used for copying properties that are one-layer deep. (One-layer deep means there are no nested objects).

How do I copy properties from one object to another in blender?

Select more than one object, press Ctrl - C to copy attributes from active to selected, you'll see the following menu: Each item on the menu will copy some attributes from the active (last selected object) to all the other selected items: Copy Location.

How do you copy properties from one object to another object in JavaScript?

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.


2 Answers

Use Object.assign(obj1, obj2); (if the properties exist in the latter) which is native in ES6 (no underscore.js is required).

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. More info here.

Example:

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj);

Alternatively use undescore.js

_.extend(destination, *sources)

or

_.extendOwn(destination, *sources)

Detailated information can be found here: http://underscorejs.org/#extend

like image 178
GibboK Avatar answered Sep 21 '22 18:09

GibboK


One lazy option is:

_.extend(a, _.pick(b, _.keys(a)));

_.pick filters the source object by using the .keys of the destination object and the result is used for extending the destination object.

If you don't want to modify the original objects just pass an empty object to the _.extend function.

_.extend({}, a, _.pick(b, _.keys(a)));
like image 22
undefined Avatar answered Sep 20 '22 18:09

undefined