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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Are you using a library there?
Hi Manish, now it leaves out the properties in b and updates only the ones in a.
wow, if you want b also to be updated according to a, call extend(b,a); what's the point of overwriting one of the objects then?? anyways
0

It's simple

for (var p in a)
   b[p] = a[p];

2 Comments

but what about nested jsons , how do i acheive the result ?
this case you'll need to use a recursion for nested objects. Use instanceof to detect it.
-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.