...

View Full Version : How to merge two json objects?



djiao
10-20-2008, 05:15 AM
I have two json object

config1 = {
title: "title",
author: "jon"
}

config2 = {
content: "abc",
publisher: "cde"
}

How can I merge them easily?

Thank you!

liorean
10-20-2008, 06:42 AM
var
i;
for(i in config2)
config1[i]=config2[i];

rnd me
10-20-2008, 07:49 AM
the above code will drege up prototypes, which you probably don't want.

try this for an easy way to merge without duping prototype members:


Object.prototype.merge = (function (ob) {var o = this;var i = 0;for (var z in ob) {if (ob.hasOwnProperty(z)) {o[z] = ob[z];}}return o;})

usage:


var a = {a:1}
var b = {b:2}

var c = a.merge(b); // === {a:1,b:2}

liorean
10-20-2008, 08:00 AM
the above code will drege up prototypes, which you probably don't want.The only object in the prototype chain is Object.prototype. If anyone modifies this, their code is likely to break other code. The Prototype library did this but had to change that a while back. Most other commonly used libraries duck the whole issue by refraining from modifying built-in prototypes. It's not likely to be a problem, in other words.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum