Copy properties deeply between two objects.
-
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.b1',
'b.b2': 'f.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(srcInfo) {
if (srcInfo.keyChain === 'a') {
return srcInfo.value * 2;
}
if (srcInfo.keyChain === 'b.b1') {
return srcInfo.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 = [ '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.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(srcInfo) {
if (srcInfo.keyChain === 'd') {
return undefined;
} else {
return srcInfo.value;
}
});
-
You can operate the parent node object directly in converter.
var src = { a: 1, b: 2 };
var dst = {};
copyProps(src, dst, function(srcInfo, dstInfo) {
Object.defineProperty(dstInfo.parent, dstInfo.key, {
writable: false,
enumerable: true,
configurable: false,
value: srcInfo.value * 2
})
});
dst
dst.a = 9
dst