0

Have u merged two jsons in javascript ??

Problem:

a={id:123,name:john,status:success};
b={id:123,status:inprocess,transId:245};

Output json should be like

{id:123,name:john,status:success,transId:245};

All the values from a should override the ones in b and also the uncommon key/values should appear in output json.

I tried out some recursive options but cudnt acheive the output.

ѕтƒ
  • 3,547
  • 10
  • 47
  • 78
Krithika Vittal
  • 1,477
  • 2
  • 16
  • 32
  • 3
    That's not JSON, that is Javascript objects. JSON is a test format for representing objects. – Guffa Feb 26 '13 at 11:20
  • It's been asked so many times: http://stackoverflow.com/questions/4154712/javascript-extending-an-object-question http://stackoverflow.com/questions/10430279/javascript-object-extending http://stackoverflow.com/questions/5585168/javascript-extending-object-with-multiple-properties – oleq Feb 26 '13 at 11:22
  • Hi oleq, i tried those links but cudnt achieve the needed result.I was careful to already search the stack before asking – Krithika Vittal Feb 26 '13 at 11:38

3 Answers3

6

your a and b variable are not valid json.

<script>
//change your a and b variable to this.
 a={id:123,name:'john',status:'success'}; 
 b={id:123,status:'inprocess',transId:245};
$(document).ready(function(){

  $.extend(a,b);

});
</script>

and a will have structure like

{
    id: 123
    name: "john"
    status: "inprocess"
    transId: 245
 
}

I've used jquery api

update.

without jquery

   a={id:123,name:'john',status:'success'}; 
   b={id:123,status:'inprocess',transId:245};

  extend(a,b);

where extend function is:

 function extend(a, b){
    for(var key in b)
        if(b.hasOwnProperty(key))
            a[key] = b[key];
    return a;
 }

ref1 ,ref2 , ref3

Community
  • 1
  • 1
Manish Mishra
  • 12,163
  • 5
  • 35
  • 59
0

It's simple

for (var p in a)
   b[p] = a[p];
Damask
  • 1,754
  • 1
  • 13
  • 24
-1
let x = {
  a: 1,
  b: 2,
  c: 3  
}

let y = {
  c: 4, 
  d: 5,
  e: 6
}

let z = Object.assign(x, y)

console.log(z)

z:
{
  a:1,
  b:2,
  c:4, 
  d:5,
  e:6,
}

---> NOTICE : the object z take the y's c attribute

Matt
  • 1,518
  • 4
  • 16
  • 30
user2898676
  • 19
  • 1
  • 4