3 回答
TA贡献1772条经验 获得超6个赞
您可以使用Object.keys()和Array.includes()来做到这一点。
var data = {
"48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
"77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}",
"83": "{\"sid\":\"83\",\"name\":\"The blahblah derp\"}",
"87": "{\"sid\":\"87\",\"name\":\"The derpy title 4\"}"
};
var obj1 = {
"48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
"77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}"
};
var result = {};
var keys = Object.keys(obj1);
for (var key in data) {
if (!keys.includes(key)) {
result[key] = data[key];
}
}
console.log(result);
TA贡献1878条经验 获得超4个赞
一种面向对象的方法,使用reduce.
const obj1 = {
'48': '{"sid":"48","name":"title 1"}',
'77': '{"sid":"77","name":"The blahblah title"}',
}
const obj2 = {
'48': '{"sid":"48","name":"title 1"}',
'77': '{"sid":"77","name":"The blahblah title"}',
'83': '{"sid":"83","name":"The blahblah derp"}',
'87': '{"sid":"87","name":"The derpy title 4"}',
}
const combinedObject = { ...obj1, ...obj2 }
const diff = Object.entries(combinedObject).reduce((acc, [key, value]) => {
if (
!Object.values(obj1).includes(value) ||
!Object.values(obj2).includes(value)
)
acc[key] = value
return acc
}, {})
console.log(diff)
这种方法将适用于多个对象,并且不会将一个对象视为主要对象进行比较。
TA贡献1811条经验 获得超4个赞
你可以使用Object.prototype.entries和Array.prototype.reduce。
const a = {
"48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
"77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}"
};
const b = {
"48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
"77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}",
"83": "{\"sid\":\"83\",\"name\":\"The blahblah derp\"}",
"87": "{\"sid\":\"87\",\"name\":\"The derpy title 4\"}"
};
const c = Object.entries(b).reduce((c, [k, v]) => Object.assign(c, a[k] ? {} : { [k]: v }), {});
console.log(c);
添加回答
举报