如何合并两个只有唯一或不同值的复杂JSON对象,这些值只显示在结果数组中
How can I merge two complex JSON objects with only unique or different values only showing in resultant array
如果我有两个复杂的JSON对象,比如:
{
"name": "foo",
"class": "top",
"plop": {"class4": "A", "class3": "C", "class2": "B"}
}
和
{
"name": "foo",
"clank": "poop",
"class": "flop",
"plop": {"class4": "A", "class3": "A", "class2": "B"}
}
我如何合并它们,使得结果对象中只有唯一或不同的值?像这样:
{
"clank": "poop",
"class": "flop",
"plop": {"class3": "A"}
}
根据Markus对这个问题的回答,我能够解决这个问题:如何动态合并两个JavaScript对象的属性?
function MergeRecursiveDiff(obj1, obj2) {
for (var p in obj2) {
try {
// Property in destination object set; update its value.
if ( obj2[p].constructor==Object ) {
obj1[p] = MergeRecursiveDiff(obj1[p], obj2[p]);
} else {
//Here, I test if the objects are already the same
if(obj1[p] === obj2[p]) {
//If they're the same, I delete the first object
delete(obj1[p]);
} else {
obj1[p] = obj2[p];
}
}
} catch(e) {
// Property in destination object not set; create it and set its value.
obj1[p] = obj2[p];
}
}
return obj1;
}
根据您喜欢的JS编程风格,以下内容可能被认为是紧凑可读的:
function find_diff(o1, o2) {
// determine if something is a non-null object
function is_object(o) { return typeof o === 'object' && o; }
// handle case where objects are equal or either is undefined
if (o1===o2 || o1===undefined && o2===undefined) { return undefined; }
if (o1===undefined) { return o2; }
if (o2===undefined) { return o1; }
// implement semantics that second value "wins"
if (!is_object(o1) || !is_object(o2)) { return o2; }
// iterate over combined set of keys, constructing a resulting object of diffs
return Object.keys(o1).concat(Object.keys(o2)).reduce(function(result, key) {
var val1 = o1[key], val2 = o2[key];
// find resulting value for this key, based on its presence on one side only,
// or diff of both values
var ret = key in o1 ? key in o2 ? find_diff(val1, val2) : val1 : val2;
// if there is a meaningful (non-undefined) diff, add to result
if (ret !== undefined) {
result = result || {};
result[key] = ret;
}
return result;
}, undefined);
}
相关文章:
- 如何使用javascript过滤复杂的json对象
- 解析复杂的json-jquery
- 使用angular显示复杂json中的列表
- 关于复杂JSON解析(angularjs和javascript)的问题
- 复杂的 JSON 结构 + 道场选择
- 从一个复杂的JSON对象打印每个JSON输入路径
- Restangular:无法发布复杂的json参数
- 如何知道一个特定的值在复杂的JSON中是否可用
- 如何使用Angular显示嵌套在ng网格中的类似json的复杂内容
- 解析并构造一个复杂的json
- JavaScript 从复杂的 JSON 中获取数据
- 使用 javascript 将复杂的 json 记录推送到 json 变量中
- 如何过滤一些看起来非常复杂的JSON数据并将其用于传单.js中的标记
- 使用 AngularJS 的复杂 JSON 响应
- 访问复杂的 JSON 对象
- JSON.stringify 在解析复杂对象时返回空对象
- 复杂的结构化 JSON 迭代
- 在纯Javascript中读取复杂的JSON
- 使用 Javascript 将 JSON 复杂化为 HTML 表
- 在ng-grid中显示json复杂字符串