function to copy objects

This commit is contained in:
Timo Hocker 2020-03-10 10:46:12 +01:00
parent b72444f8c0
commit cbe4589476
3 changed files with 27 additions and 1 deletions

View File

@ -11,4 +11,10 @@ util.truncate_decimal(12.345678, 2);
// will return null instead of throwing on invalid json
util.try_parse_json('{{foo');
// copy an object to prevent modification of the original
const obj = {foo:'bar'};
const copy = util.copy_object(obj);
copy.foo = 'baz';
console.log(obj.foo); // bar
```

View File

@ -32,7 +32,19 @@ function try_parse_json (text) {
return null;
}
/**
* copy an object to prevent modification to the original
*
* @param {object} obj object to copy
* @returns {object} copy
*/
function copy_object (obj) {
return JSON.parse (JSON.stringify (obj));
}
module.exports = {
truncate_decimal,
try_parse_json
try_parse_json,
copy_object
};

View File

@ -30,3 +30,11 @@ test ('try_parse_json should fail', (t) => {
t.is (json, null);
});
});
test ('copy object', (t) => {
const obj = {foo:'bar'};
const copy = util.copy_object(obj);
copy.foo = 'baz';
t.is(copy.foo, 'baz');
t.is(obj.foo, 'bar');
});