Reputation: 1414
I have 2 variable masterdata
and datatoedit
.
masterdata
have array value and datatoedit
have object value.
I want to copy data 1 from masterdata
to variable datatoedit
, so I write like this:
this.datatoedit = this.masterdata[0]
But when I edit data from datatoedit
on form data on masterdata[0]
also changed.
How to prevent masterdata[0]
from changed when I edit datatoedit
?
Upvotes: 2
Views: 102
Reputation: 402
You can also do this using lodash function clonedeep. It will not copy the references.
data_to_edit = _.cloneDeep(masterdata[0])
You can now modify data_to_edit as your wish.
Upvotes: 2
Reputation: 166
The accepted answer can go wrong if the masterdata
elements have nested objects like
{
name: 'John',
age: 30,
address: {
street: 'ChurchStreet',
city: 'Bangalore',
state: 'KA'
}
}
var masterdata = [
{
name: 'John',
age: 30,
address: {
street: 'ChurchStreet',
city: 'Bangalore',
state: 'KA'
}
},
{
name: 'Jane',
age: 26,
address: {
street: 'West of Chord',
city: 'Mumbai',
state: 'MH'
}
}
];
// With spread operator
var datatoedit = {...masterdata[0]};
datatoedit.age = 32;
datatoedit.address.street = 'Infantry Road';
console.log('With spread operator');
console.log('masterdata[0]: ' + JSON.stringify(masterdata[0]));
console.log('datatoedit: ' + JSON.stringify(datatoedit));
// With Object.assign()
datatoedit = Object.assign({}, masterdata[0]);
datatoedit.age = 35;
datatoedit.address.street = 'Brigade Road';
console.log('With Object.assign()');
console.log('masterdata[0]: ' + JSON.stringify(masterdata[0]));
console.log('datatoedit: ' + JSON.stringify(datatoedit));
// Now with JSON.parse() and JSON.stringify()
datatoedit = JSON.parse(JSON.stringify(masterdata[0]));
datatoedit.age = 35;
datatoedit.address.street = 'West of Chord Road';
console.log('With JSON.parse() and JSON.stringify()');
console.log('masterdata[0]: ' + JSON.stringify(masterdata[0]));
console.log('datatoedit: ' + JSON.stringify(datatoedit));
As you can see, in case of nested objects, both spread operator and Object.assign() can go wrong as they do shallow copy.
Combining JSON.parse() and JSON stringify() creates the effect of deep copy and hence it works fine all cases. (Though these functions are not meant for deep copy as such).
Upvotes: 2
Reputation: 1493
You can use ES6 Spread syntax to make an object copy:
this.datatoedit = {...this.masterdata[0]}
Upvotes: 3