A JavaScript function for copying object properties

A simple but reasonably feature rich object properties copy function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
function copy(source, target, config = {}) {
const {
list = [],
blacklist = !list.length,
whitelist = !blacklist,
map = {},
parse = {},
override = true
} = config;
for (let [key, val] of Object.entries(source)) {
const inlist = list.indexOf(key) !== -1;
const prop = map[key] || key;
if (
((blacklist && !inlist) || (whitelist && inlist))
&& (!target[prop] || override)
) target[prop] = typeof parse[key] === 'function' ? parse[key](val) : val
}
return target;
};
let source;
let target;
source = {foo: 'sfoo', bar: 'sbar'};
target = {foo: 'tfoo'};
copy(source, target); // {foo: 'sfoo', bar: 'sbar'}
source = {foo: 'sfoo', bar: 'sbar'};
target = {foo: 'tfoo'};
copy(source, target, {override: false}); // {foo: 'tfoo', bar: 'sbar'}
source = {foo: 'sfoo', bar: 'sbar', baz: 'sbaz'};
target = {foo: 'tfoo'};
copy(source, target, {list: ['baz']}); // {foo: 'tfoo', baz: 'sbaz'}
source = {foo: 'sfoo', bar: 'sbar', baz: 'sbaz'};
target = {foo: 'tfoo'};
copy(source, target, {list: ['baz'], blacklist: true}); // {foo: 'sfoo', bar: 'sbar'}
source = {foo: 'sfoo', bar: 'sbar'};
target = {foo: 'tfoo', bar: 'tbar'};
copy(source, target, {map: {foo: 'qux'}}); // {foo: "tfoo", bar: "sbar", qux: "sfoo"}
source = {foo: 'sfoo', bar: 'sbar'};
target = {foo: 'tfoo'};
copy(source, target, {
parse: {
bar: str => str.split('').reverse().join('')
}
}); // {foo: 'sfoo', bar: 'rabs'}