skip to Main Content
json1 = {
      "color": "#101017",
      "fontSize": "15px",
      "h1": {
        "color": "#101017",
        "fontSize": "32px"
      }
}


json2 = {
     "h1": {
        "color": "blue"
     }
}

And output should be

json = {
      "color": "#101017",
      "fontSize": "15px",
      "h1": {
        "color": "blue",
        "fontSize": "32px"
      }
}

I was trying to merge two json where second one overrides the first one with a native way in javascript.

2

Answers


  1. These "JSON objects" you posted can be treated as JavaScript objects, hence we could write a simple object merging function. Note that this function will merge any first child objects inside the object properties (like in your example), but if you make even more further child objects it will not work properly.

    function objectMerge (first, second) {
        if (typeof first !== "object" || typeof second !== "object") return false;
    
        const keys = Object.keys(second);
        let ret = first;
        for (let i = 0; i < keys.length; i++) {
            if (ret[keys[i]] !== undefined) {
                if (typeof second[keys[i]] === "object") {
                    if (typeof ret[keys[i]] !== "object") {
                        delete ret[keys[i]];
                        ret[keys[i]] = {};
                    }
                    const keys2 = Object.keys(second[keys[i]]);
                    for (let j = 0; j < keys2.length; j++) ret[keys[i]][keys2[j]] = second[keys[i]][keys2[j]];
                }
                else {
                    if (typeof ret[keys[i]] === "object") delete ret[keys[i]];
                    ret[keys[i]] = second[keys[i]];
                }
            }
            else ret[keys[i]] = second[keys[i]];
        }
        return ret;
    }
    
    
    const json1 = {
          "color": "#101017",
          "fontSize": "15px",
          "h1": {
            "color": "#101017",
            "fontSize": "32px"
          }
    };
    
    const json2 = {
         "h1": {
            "color": "blue"
         }
    };
    
    console.log(objectMerge(json1, json2));
    Login or Signup to reply.
  2. Something like this, maybe?

    function myMerge(current, update) {
       return Object.keys(update).reduce((acc, key) => {
            if(!acc.hasOwnProperty(key) || typeof update[key] !== 'object') {
                acc[key] = update[key]
            } else {
                myMerge(current[key], update[key])
            }
            return acc
        }, current)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search