On Aug 3, 2016, at 7:43 PM, Tippur wrote:

> Changed it to
> 
> ##########
> '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;

Here, you're making jsontemp a reference to the same block of memory used by 
jsonstr. Later, when you modify jsontemp.a, it's the same as modifying 
jsonstr.a. Then later, when you push jsontemp onto the payload array, you're 
pushing a reference to that same jsontemp / jsonstr block of memory. Since 
that's in a forEach it happens multiple times, but each time, you're pushing a 
reference to the same block of memory onto the array, which is why when you 
print the array later, every item is the same, and has the values from the last 
loop iteration.

The fix is to make jsontemp an actual copy of jsonstr, with its own memory that 
you can modify independently, e.g.:

                var jsontemp=Object.assign({}, jsonstr);



>                 jsontemp.a=item;
> 

> 
> 
>                 console.log(jsontemp);
> 
> 
> 
>                 payload.push(jsontemp);
> 

> 
>         });
> 
> 
> 
> }
> 
> 
> 
> console.log(payload);
> 
> 
> 
> ####################
> 
> 
> 
> i get the same result.

-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/C2B33895-7BFB-493E-88E3-534208BA85CE%40ryandesign.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to