-1
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.

Gonzalo S
  • 896
  • 11
  • 19
  • 1
    Please may you correct your terminology? The provided code is not JSON. They are JS objects. – evolutionxbox Mar 16 '23 at 15:19
  • 2
    Does [this](https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge) answer your question? – Palladium02 Mar 16 '23 at 15:26
  • This is called a deep merge. Please refer to the answer posted by @Palladium02 to solve the issue according to the specified output. – Gonzalo S Mar 16 '23 at 16:49

2 Answers2

0

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));
Toka47
  • 31
  • 3
0

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