function to copy objects
This commit is contained in:
parent
b72444f8c0
commit
cbe4589476
@ -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
|
||||
```
|
||||
|
14
index.js
14
index.js
@ -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
|
||||
};
|
||||
|
@ -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');
|
||||
});
|
||||
|
Loading…
x
Reference in New Issue
Block a user