layout: post title: How to Copy JSON Object
Sometimes server respond with data like this:
{
"code": 200,
"msg": {
"list": [
{
"text": "string 1",
"value": 1
},
{
"text": "string 2",
"value": 2
}
]
}
}
And we modify the list like this:
let list = ret.msg.list;
list.push({
text: 'string 3',
value: 3
});
ret.msg.list === [
{
text: 'string 1',
value: 1
},
{
text: 'string 2',
value: 2
},
{
text: 'string 3',
value: 3
}
]
Now, we will find the original response modified. What if I want it not to be changed.
Because javascript passing variables by pointer, which means list
above is always pointing to the array that server responded.
So when we modify list
, will simultaneously modify the server response.
This will happen when we cope with arrays and js objects.
let list = ret.msg.list.map(item => {
item.text,
item.value
});
list.push({
text: 'string 3',
value: 3
});
ret.msg.list === [
{
text: 'string 1',
value: 1
},
{
text: 'string 2',
value: 2
}
]
We can use jQuery
, underscore
, lodash
.
let list = $.extend({}, ret.msg).list;
let list = _.extend({}, ret.msg).list;
let list = _.clone(ret.msg.list, true);
let list = _.cloneDeep(ret.msg.list);
let list = JSON.parse(JSON.stringify(ret.msg.list));
But this only works for JSON objects, removes Function
, undefined
values, and keeps what JSON objects takes.
The keys must be strings (i.e. enclosed in double quotes ") in JSON.
The values can be either: