{ a: 'x', rest: 'fdsf', ff: 'll' } and { a: 'y', rest: 'fdsf', ff: 'll' }
var str='{ \
"a": ["x", "y"], \
"rest": "fdsf", \
"ff": "ll" \
}'
jsonstr=JSON.parse(str);
var payload=[];
if (Array.isArray(jsonstr['a'])){
console.log("Is array");
var payload=[];
jsonstr['a'].forEach(function(item, index) {
console.log(item);
jsontemp=jsonstr;
jsontemp.a=item;
console.log(jsontemp);
payload.push(jsontemp);
});
}
console.log(payload);
[ { a: 'y', rest: 'fdsf', ff: 'll' },
{ a: 'y', rest: 'fdsf', ff: 'll' } ]
As you can see, the object appended to the final payload has the same element (payload.a)
What am I doing wrong?
- Shekar
'use strict'
var str='{ \
"a": ["x", "y"], \
"rest": "fdsf", \
"ff": "ll" \
}'
var jsonstr=JSON.parse(str);
var payload=[];
if (Array.isArray(jsonstr['a'])){
console.log("Is array");
var payload=[];
jsonstr['a'].forEach(function(item, index) {
console.log(item);
var jsontemp=jsonstr;
jsontemp.a=item;
console.log(jsontemp);
payload.push(jsontemp);
});
}
console.log(payload);
####################
i get the same result.
In your code you are doing this:
var jsontemp=jsonstr;
This is not making a copy of jsonstr, it is making an alias that points to the same object. This means that later when you are modifying jsontemp.a you are also modifying jsonstr.a and when you push jsontemp on to your array, you are pushing a reference on to the list.
In other words, you are modifying jsonstr in place and then adding it to an array each time you do it.
~Ryan
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/0c07b08f-3f2f-49e4-b268-179fb840ea64%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
~Ryan