JSFiddle - React, Tailwind, and code Playground
JavaScript
var obj1 = {
astring: "stringobj1",
anum: 1,
anum2: 2,
data1: {
data11: [
{
id: 2,
comment: "comment2"},
{
id: 3,
comment: "comment3"},
{
id: 4,
comment: "comment4"}],
data12: ""
},
data: [
{
id: 1,
comment: "comment1"},
{
id: 2,
comment: "comment2"},
{
id: 3,
comment: "comment3"}
]
};
var obj2 = {
anum2: 3,
astring: "stringobj2",
data1: {
data11: [
{
id: 2,
comment: "comment12"},
{
id: 3,
comment: "comment13"},
{
id: 4,
comment: "comment14"}],
data12: ""
},
data: [
{
id: 2,
comment: "comment2"},
{
id: 3,
comment: "comment3"},
{
id: 4,
comment: "comment4"}
],
data2: [
{
id: 2,
comment: "comment2"},
{
id: 3,
comment: "comment3"},
{
id: 4,
comment: "comment4"}]
};
$(document).ready(function() {
console.log(mergeDeep(obj1, obj2));
});
function mergeDeep(o1, o2) {
var tempNewObj = o1;
//if o1 is an object - {}
if (o1.length === undefined && typeof o1 !== "number") {
$.each(o2, function(key, value) {
if (o1[key] === undefined) {
tempNewObj[key] = value;
} else {
tempNewObj[key] = mergeDeep(o1[key], o2[key]);
}
});
}
//else if o1 is an array - []
else if (o1.length > 0 && typeof o1 !== "string") {
$.each(o2, function(index) {
if (JSON.stringify(o1).indexOf(JSON.stringify(o2[index])) === -1) {
tempNewObj.push(o2[index]);
}
});
}
...