Skip to content

Instantly share code, notes, and snippets.

@ahmehri
Created July 5, 2019 15:20
Show Gist options
  • Save ahmehri/67c69a65e06049ee285f27efb84ce8d4 to your computer and use it in GitHub Desktop.
Save ahmehri/67c69a65e06049ee285f27efb84ce8d4 to your computer and use it in GitHub Desktop.
const { assign, cloneDeep } = require('lodash');
let obj = {
type: {
values: {
results: [1, 2]
}
}
};
let copy;
// simple assignment => doesn't work
copy = obj;
copy
copy.type.values.results.push(3);
console.log(JSON.stringify(copy))
console.log(JSON.stringify(obj))
// spread => mutation => doesn't work
obj = {
type: {
values: {
results: [1, 2]
}
}
};
copy = {
...obj
}
copy
copy.type.values.results.push(3);
console.log(JSON.stringify(copy))
console.log(JSON.stringify(obj))
// lodash assing => mutation => doesn't work
obj = {
type: {
values: {
results: [1, 2]
}
}
};
copy = assign(obj, {});
copy
copy.type.values.results.push(3);
console.log(JSON.stringify(copy))
console.log(JSON.stringify(obj))
// cloneDeep => works
obj = {
type: {
values: {
results: [1, 2]
}
}
};
copy = cloneDeep(obj);
copy
copy.type.values.results.push(3);
console.log(JSON.stringify(copy))
console.log(JSON.stringify(obj))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment