我有第一个对象
obj1 = {lastName: "", address1: "Some address"}
第二个对象:
obj2 = {lastName: "Salivan", address1: "1200 Getty Center Dr"}
在结果对象中:
obj3 = {lastName: "Salivan", address1: "Some address"}
对我来说最简单的方法是执行以下操作:
const newObject = {
...obj1,
...obj2,
}
问题是,它会凌驾于你的价值观之上!所以最好不要将两个相似的对象合并为一个,通常用于更新一个对象的值或将不同的对象合并为一个。
按照
@AlexSp3
的建议,您还可以:
obj3 = Object.assign(obj1, obj2)
对于您的具体情况:
const obj3 = {
key1: '',
key2: '',
}
if (!obj1.key1) {
obj3.key1 = obj2.key1;
} else {
obj3.key1 = obj1.key1;
}
// ... repeat with key2
如果目标是选择非错误值...
let obj1 = {
lastName: "",
address1: "Some address"
}
let obj2 = {
lastName: "Salivan",
address1: "1200 Getty Center Dr"
}
let result = Object.fromEntries(
Object.entries(obj1).map(([key, value]) => {
return [key, value || obj2[key]]
})
);
console.log(result)
不覆盖值:
const obj1 = {
key1: 1,
key2: 2
}
const obj2 = {
key2: 3,
key3: 4
}
function mergeObjects(obj0, obj1) {
// merge object keys into array
const joined = [...Object.keys(obj0), ...Object.keys(obj1)]
// remove duplicates
const uniqueKeys = [...new Set(joined)]
// merge obj0 and obj1 into new Object
// obj1 overrides obj0
const newObject = {}
uniqueKeys.forEach(key => {
if (obj0[key] !== undefined && obj1[key] !== undefined) {
newObject[key] = [obj0[key], obj1[key]]
} else if (obj0[key] === undefined && obj1[key] !== undefined) {
newObject[key] = obj1[key]
} else if (obj0[key] !== undefined && obj1[key] === undefined) {
newObject[key] = obj0[key]
} else {
console.log('OBJECT MERGING ERROR')
}
})
return newObject
}
console.log(mergeObjects(obj1, obj2))