(function() {
'use strict';
function diffObj(obj1, obj2, ref) {
var prefix = ref || '';
var res = [];
if (!_.isUndefined(obj1) && _.isUndefined(obj2)) {
res.push({
currentVal: prefix + ' : ' + JSON.stringify(obj1),
newVal: 'DELETED'
});
} else if (_.isUndefined(obj1) && !_.isUndefined(obj2)) {
res.push({
currentVal: 'DELETED',
newVal: prefix + ' : ' + JSON.stringify(obj2)
});
}
if (_.isUndefined(obj1) || _.isUndefined(obj2)) {
return _.flattenDeep(res);
}
var keys = _.uniq(_.keys(obj1).concat(_.keys(obj2)));
_(keys).forEach(function(key) {
var value1 = obj1[key];
var value2 = obj2[key];
if (!_.isUndefined(value1) && _.isUndefined(value2)) {
res.push({
currentVal: prefix + key + ' : ' + value1,
newVal: 'DELETED'
});
} else if (_.isUndefined(value1) && !_.isUndefined(value2)) {
res.push({
currentVal: 'DELETED',
newVal: prefix + key + ' : ' + value2
});
} else if (_.isArray(value1) && _.isArray(value2)) {
var entries = Math.max(value1.length, value2.length);
for (var i = 0; i < entries; i++) {
res.push(diffObj(value1[i], value2[i], prefix + key + '[' + i + '].'));
}
} else if (_.isObject(value1) && _.isObject(value2)) {
res.push(diffObj(value1, value2, prefix + key + '.'));
} else if (!_.isEqual(value1, value2)) {
res.push({
currentVal: prefix + key + ' : ' + value1,
newVal: prefix + key + ' : ' + value2
});
}
});
return _.flattenDeep(res);
}
var json1 = {
"id": 1,
"title": "Object 1",
"description": "Object 1 Description",
"test": "foo bar",
"relations": {
"tools": [{
"id": 2,
"title": "my first tool",
"description": "tools description",
"types": [{
"id": 123,
"name": "test"
}, {
"id": 111,
"name": "test2"
}]
}],
"training": [{
"id": 3,
"title": "Test training",
"description": "training Description",
"trainingTypes": [{
"id": 1,
"name": "online"
}, {
"id": 2,
"name": "in-person"
}, {
"id": 3,
"name": "boot camp"
}]
}]
}
};
var json2 = {
"id": 1,
"title": "Object 1 UPDATED",
"description": "Object 1 Description UPDATED",
"relations": {
"tools": [{
"id": 2,
"title": "my first tool UPDATED",
"description": "tools description",
"types": [{
"id": 123,
"name": "test"
}]
}],
"training": [{
"id": 3,
"title": "Test training",
"description": "training Description UPDATED",
"trainingTypes": [{
"id": 1,
"name": "online"
}, {
"id": 3,
"name": "boot camp"
}]
}]
}
};
var res = diffObj(json1, json2);
res = res.map(function(d) {
return '<tr><td>' + d.currentVal + '</td><td>' + d.newVal + '</td></tr>';
});
$('#tableResult > tbody').append(res);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
<table id="tableResult" class="table table-hover table-striped">
<thead>
<tr>
<th>
current
</th>
<th>
new
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
"JSONオブジェクト" のようなものはありません。私はあなたが "JavaScriptオブジェクト"を意味すると思います。 –