Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Oct 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How to merge two json objects?

    I have two json object

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

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

    How can I merge them easily?

    Thank you!

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    UmeŚ, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Code:
    var
        i;
    for(i in config2)
        config1[i]=config2[i];
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    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:

    Code:
    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:

    Code:
    var a = {a:1}
    var b = {b:2}
    
    var c = a.merge(b); // === {a:1,b:2}
    Last edited by rnd me; 10-20-2008 at 07:52 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #4
    Master Coder
    Join Date
    Feb 2003
    Location
    UmeŚ, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Quote Originally Posted by rnd me View Post
    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.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •