3

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

3 Answers 3

3

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.

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

3 Comments

This will certainly work but i dont think its worth adding a library just for this when it can be achieved fairly easily without.
I didn't suggest to use the library, just to look at its source (the implementation of the Object.extend method).
Ahh i saw prototype and thought you were suggesting he add the library... my bad.
0

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.

Comments

0

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

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.