我在这里需要帮助,因为我找不到合适的解决方案: 我有两个对象:
obj1 = {
name: '112',
surname: { test: '123', other: '124' },
age: 151,
height: '183',
weight: 80
};
和
obj2 = {
name: '114',
surname: { test: '124' },
age: 151,
height: 184,
weight: 81
};
新对象必须具有以下输出:
new = {
name: '114',
surname: { test: '124', other: '124' },
age: 151,
height: 184,
weight: 81
};
您可以看到,在姓氏属性中保留了其他属性: 我已经尝试过类似的方法,但是它不起作用,并且必须有一个更简单的解决方案:
const newObje = Object.keys(obj2).reduce(newObj, key) => {
if (typeof (obj2[key]) === 'string' || obj2[key] === 'number') {
newObj[key] = obj2[key];
}
if (typeof (obj2[key]) === 'object' || obj2[key] === 'array') {
}
}
答案 0 :(得分:2)
您可以使用合并功能,并用最后一个值覆盖值。
function merge(...objects) {
function m(t, s) {
Object.entries(s).forEach(([k, v]) => {
t[k] = v && typeof v === 'object' ? m(t[k] || {}, v) : v;
});
return t;
}
return objects.reduce(m, {});
}
var obj1 = { name: '112', surname: { test: '123', other: '124' }, age: 151, height: '183', weight: 80 },
obj2 = { name: '114', surname: { test: '124' }, age: 151, height: 184, weight: 81 },
result = merge(obj1, obj2);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您可以使用lodash
.merge
_.merge(obj1 , obj2)
如您在文档中所见,它将深度合并两个对象
此方法类似于_.assign,不同之处在于它将源对象自己的和继承的可枚举字符串键属性递归合并到目标对象中。如果存在目标值,则将解析为未定义的源属性。数组和普通对象属性以递归方式合并。其他对象和值类型被赋值覆盖。源对象从左到右应用。后续源将覆盖先前源的属性分配。
let obj1 = {
name: '112',
surname: { test: '123', other: '124' },
age: 151,
height: '183',
weight: 80
};
let obj2 = {
name: '114',
surname: { test: '124' },
age: 151,
height: 184,
weight: 81
};
let newObj = _.merge(obj1, obj2)
console.log(newObj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>