mat
mat

Reputation: 2617

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
  }
};

Upvotes: 3

Views: 163

Answers (3)

J. K.
J. K.

Reputation: 8368

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.

Upvotes: 3

pete
pete

Reputation: 25091

Here's one way, although I'm sure there are more elegant solutions.

var jason1 = {
    "book1": {
        "price": 10,
        "weight": 30
    },
    "book2": {
        "price": 40,
        "weight": 60
    }
};
var jason2 = {
    "book3": {
        "price": 70,
        "weight": 100
    },
    "book4": {
        "price": 110,
        "weight": 130
    }
};
var jasons = {};
var key;
for (key in jason1) {
    if (jason1.hasOwnProperty(key) && !(jasons.hasOwnProperty(key))) {
        jasons[key] = jason1[key];
    }
}
for (key in jason2) {
    if (jason2.hasOwnProperty(key) && !(jasons.hasOwnProperty(key))) {
        jasons[key] = jason2[key];
    }
}
console.log(jasons);

Upvotes: 0

prodigitalson
prodigitalson

Reputation: 60413

You jsut need to manually iterate over them:

var both = [json1, json2],
    jasons = {};


for (var i=0; i < both.length; i++) {
  for (var k in both[i]) {
    if(both[i].hasOwnProperty(k)) {
       jasons[k] = both[i][k];
    }
  }
}

Heres a working fiddle. You might want to think about what happens if there are duplicate keys though - for example what if book3 exists in both json objects. With the code i provided the value in the second one always wins.

Upvotes: 0

Related Questions