如何返回对象对象被覆盖的结果
我只想返回使用Ecmascript6在firstObject中覆盖firstObject的那些元素
var firstObject = {
one: 1,
four: 55,
six: 6
}
var secondObject = {
one: 1,
two: 2,
three: 3,
four: 4
}
returnObject = { four:55 }
答案 0 :(得分:1)
如果要检查两个对象上都存在哪些属性以及值的差异,可以使用Object.entries
将第一个对象转换为数组。使用reduce
遍历数组,检查并构造新对象。
var firstObject = {
one: 1,
four: 55,
six: 6
}
var secondObject = {
one: 1,
two: 2,
three: 3,
four: 4
}
var returnObject = Object.entries(firstObject).reduce((c, [k, v]) => {
if (secondObject[k] !== undefined && v !== secondObject[k]) c[k] = v;
return c;
}, {});
console.log(returnObject);
一个班轮代码:
var returnObject = Object.entries(firstObject).reduce((c, [k, v]) => secondObject[k] !== undefined && v !== secondObject[k] ? Object.assign(c, {[k]: v}) : c, {})
答案 1 :(得分:1)
您可以获取条目,过滤和映射新对象。
var firstObject = { one: 1, four: 55, six: 6 },
secondObject = { one: 1, two: 2, three: 3, four: 4 },
result = Object.assign({}, ...Object
.entries(firstObject)
.filter(([k, v]) => k in secondObject && secondObject[k] !== v)
.map(([k, v]) => ({ [k]: v }))
);
console.log(result);