Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining 2 jsons objects

I've 2 json object that I would like to combine. I tried using concat and merge function, but the result is not what I want. Any help would be appreciated.

var jason1 = 
{
  "book1": {
    "price": 10,
    "weight": 30
  },
  "book2": {
    "price": 40,
    "weight": 60
  }
};

and this is the other object

var jason2 =
{
  "book3": {
    "price": 70,
    "weight": 100
  },
  "book4": {
    "price": 110,
    "weight": 130
  }
};

This is what I want:

var jasons =
{
  "book1": {
    "price": 10,
    "weight": 30
  },
  "book2": {
    "price": 40,
    "weight": 60
  }
  "book3": {
    "price": 70,
    "weight": 100
  },
  "book4": {
    "price": 110,
    "weight": 130
  }
};
like image 598
mat Avatar asked Feb 24 '26 17:02

mat


1 Answers

See the source of the Object.extend method from the Prototype.js framework:

https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/object.js#L88

function extend(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
}

The usage is then…

extend(jason1, jason2);

The object jason1 now contains exactly what you want.

like image 70
J. K. Avatar answered Feb 26 '26 05:02

J. K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!