Reputation: 31
Modifying a JSON array (nested into another array) seems NOK with this code:
var names = [{'name': 'ourname'},{'name': 'yourname'}] ;
var array = [{
"year": "2015",
names
},{
"year": "2016",
names
}];
I can't modify a single name entry in "array" by doing this
array[0].names[1].name="MY NAME"
since it's actually modifying all names entry in the row "0":
Output:
0:0 ourname
0:1 MY NAME
1:0 ourname
1:1 MY NAME
Plunker here
I'm looking for a clean way to achieve a proper single modification in the name array as I'd like to avoid loops to do this.
Thanks for your help
Upvotes: 2
Views: 69
Reputation: 75
You need a key: value in an object (javascript object).
var names = [{'name': 'ourname'},{'name': 'yourname'}] ;
var array = [{
"year": "2015",
"names": names
},{
"year": "2016",
"names": names
}];
var wName = array[0].names[1].name;
// yourname
Upvotes: 0
Reputation: 9813
Because they're pointing to same array, and also, simply clone names
by .slice
is not enough, as the array contains objects
not primitive types, so you need to deep clone from the original names
and assign to each object.
So you need to change the code to :
var array = [{
"year": "2015",
names: JSON.parse(JSON.stringify(names))
}, {
"year": "2016",
names: JSON.parse(JSON.stringify(names))
}];
See the edited pluker.
I use JSON.parse(JSON.stringify(names))
to simply create do deep clone from original array here, there can have other ways.
Upvotes: 2
Reputation: 4916
You should try copying the names array, once for each "unique" use case, since Javascript sneakily has references sometimes.
One way to do it is to write a deepclone()
method that will do a deep copy of a hierarchical object.
var array = [{
"year": "2015",
names: deepclone(names)
},{
"year": "2016",
names: deepclone(names)
}];
Upvotes: 0