简体   繁体   English

使用条件将属性从一个对象复制到另一个对象

[英]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? Lazy-me想知道是否有更好的方法将一个对象(源)中的属性复制到另一个对象(目标),只有后者存在属性? It does not necessarily have to be using Underscore. 它不一定要使用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

Use Object.assign(obj1, obj2); 使用Object.assign(obj1, obj2); (if the properties exist in the latter) which is native in ES6 (no underscore.js is required). (如果属性存在于后者中),这在ES6中是原生的(不需要下划线.js)。

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. Object.assign()方法用于将所有可枚举自身属性的值从一个或多个源对象复制到目标对象。 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 或者使用unexcore.js

_.extend(destination, *sources)

or 要么

_.extendOwn(destination, *sources)

Detailated information can be found here: http://underscorejs.org/#extend 有关详细信息,请访问: http ://underscorejs.org/#extend

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. _.pick通过使用过滤对象.keys 目标对象和所述结果用于延伸目标对象。

If you don't want to modify the original objects just pass an empty object to the _.extend function. 如果您不想修改原始对象,只需将空对象传递给_.extend函数即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM