Copy properties deeply between two objects.
Install
$ npm i copy-props --save
Usage
-
Load this module :
const copyProps = require('copy-props');
-
Copy src to dst simply (and return dst) :
var src = { a: 1, b: { b1: 'bbb' }, c: 'ccc' };
var dst = { a: 2, b: { b1: 'xxx', b2: 'yyy' } };
copyProps(src, dst);
-
Copy src to dst with property mapping (and return dst) :
var src = { a: 1, b: { b1: 'bbb' }, c: 'ccc', d: 'ddd' };
var dst = { f: { a: 2, b1: 'xxx', b2: 'yyy' }, e: 'zzz' };
copyProps(src, dst, {
a: 'f.a',
'b.b1': 'f.b.b1',
'b.b2': 'f.b.b2',
'c': 'f.c',
});
-
Copy src to dst with convert function (and return dst) :
var src = { a: 1, b: { b1: 'bbb' } };
var dst = { a: 0 };
copyProps(src, dst, function(value, keychain) {
if (keychain === 'a') {
return value * 2;
}
if (keychain === 'b.b1') {
return value.toUpperCase();
}
});
-
Can use an array instead of a map as property mapping :
var src = { a: 1, b: { c: 'CCC' }, d: { e: 'EEE' } };
var dst = { a: 9, b: { c: 'xxx' }, d: { e: 'yyy' } };
var fromto = [ 'a.b.c', 'd.e' ];
copyProps(src, dst, fromto);
-
Can copy reversively (from dst to src) by reverse flag (and return src):
var src = { a: 1, b: { b1: 'bbb' }, c: 'ccc' };
var dst = { a: 2, b: { b1: 'xxx', b2: 'yyy' } };
copyProps(src, dst, true);
var src = { a: 1, b: { b1: 'bbb' }, c: 'ccc', d: 'ddd' };
var dst = { f: { a: 2, b1: 'xxx', b2: 'yyy' }, e: 'zzz' };
copyProps(src, dst, {
a: 'f.a',
'b.b1': 'f.b1',
'b.b2': 'f.b2',
'c': 'f.c',
}, true);
-
If a value of source property is undefined (when not using converter), or a result of converter is undefined (when using converter), the value is not copied.
var src = { a: 'A', b: undefined, c: null, d: 1 };
var dst = { a: 'a', b: 'b', c: 'c' };
copyProps(src, dst, function(value, key) {
if (key === 'd') {
return undefined;
} else {
return value;
}
});
API
copyProps(src, dst [, fromto] [, converter] [, reverse]) => object
Copy properties of src to dst deeply.
If fromto is given, it is able to copy between different properties.
If converter is given, it is able to convert the terminal values.
Format of fromto
fromto is a non-nested key-value object. And the keys are property key chains of src and the values are property key chains of dst.
The key chain is a string which is concatenated property keys on each level with dots, like 'aaa.bbb.ccc'
.
The following example copys the value of src.aaa.bbb.ccc
to dst.xxx.yyy
.
copyProps(src, dst, {
'aaa.bbb.ccc' : 'xxx.yyy'
})
fromto can be an array. In that case, the array works as a map which has pairs of same key and value.
API of converter
converter(srcValue, srcKeychain, dstKeyChain, dstValue) => any
converter is a function to convert terminal values of propeerties of src.
License
Copyright (C) 2016 Takayuki Sato
This program is free software under MIT License.
See the file LICENSE in this distribution for more details.