如何通过合并相同属性的值来合并两个对象?

How do I combine two objects by merging the values of same properties?

如果属性相同而不是覆盖,有没有一种方法可以通过嵌套值来组合两个对象? 例如:

const obj1 = {a:10,b:13}
const obj2 = {a:84,c:70}

desired result : 
combinedObject = {a:{0:10,1:84}, b:13, c:70}

您必须遵守对象定义规则

const obj1 = {a:10,b:13}
const obj2 = {a:84,c:70}
//it can be like this
combinedObject = {a:[10,84], b:13, c:70}
// you can access to that value like this 
let value = combinedObject.a[0];

最后,您可以使用此代码进行组合

    const obj1 = { a: 10, b: 13 };
    const obj2 = { a: 84, c: 70 };
    const props = Object.getOwnPropertyNames(obj2);
    let combinedObject = { ...obj1 };
    for (let i = 0; i < props.length; i++) {
      if (combinedObject[props[i]])
        combinedObject[props[i]] = [combinedObject[props[i]], obj2[props[i]]];
      else combinedObject[props[i]] = obj2[props[i]];
    }
    //result :{a:[10,84], b:13, c:70}

如你所愿

const obj1 = { a: 10, b: 13 };
    const obj2 = { a: 84, c: 70 };
    const props = Object.getOwnPropertyNames(obj2);
    let combinedObject = { ...obj1 };
    for (let i = 0; i < props.length; i++) {
      if (combinedObject[props[i]])
        combinedObject[props[i]] = {0:combinedObject[props[i]], 1:obj2[props[i]]};
      else combinedObject[props[i]] = obj2[props[i]];
    }
    console.log(combinedObject);
//result :{a:{0:10,1:84}, b:13, c:70}

const obj1 = { a: 10, b: 13 }
const obj2 = { a: 84, c: 70, d: 40 }

function foo(obj1, obj2) {

    const newObject = {}
    for (const key in { ...obj1, ...obj2 }) {
        const element1 = obj1[key];
        const element2 = obj2[key];
        if (element1 && element2)
            newObject[key] = [element1, element2]
        else if (element1)
            newObject[key] = element1
        else if (element2)
            newObject[key] = element2
    }
    return newObject
}
console.log(foo(obj1, obj2))

这里有两个解决方案, 第一个,将键的值合并到一个具有相同键名的对象中。 第二个,按照你说的提出合并的方法,但是维护每个键的索引稍微复杂一点,但还是可以的。

两个选项的结果看起来都是这样

// Option 1
{ a: [ 10, 11, 84 ], b: [ 13, 12 ], c: 70, d: 50 }

// Option 2
{
  a: { '0': 10, '1': 11, '2': 84 },
  b: { '0': 13, '1': 12 },
  c: 70,
  d: 50
}

这是如何实现的

const obj1 = { a: { 0: 10, 1: 11 }, b: 13 }
const obj2 = { a: 84, b: 12, c: 70, d: 50 }
const allKeys = Object.keys({ ...obj1, ...obj2 });

const merged1 = {};
for (const key of allKeys) {
    const isObj1Object = typeof obj1[key] === 'object';
    const isObj2Object = typeof obj2[key] === 'object';
    if (obj1[key] && obj2[key]) {
        merged1[key] = [
            ...(isObj1Object ? Object.values(obj1[key]) : [obj1[key]]),
            ...(isObj2Object ? Object.values(obj2[key]) : [obj2[key]]),
        ];
    } else if (obj1[key] || obj2[key]) {
        merged1[key] = obj1[key] || obj2[key];
    }
}

console.log(merged1);

const merged2 = {};
for (const key of allKeys) {
    if (obj1[key] && obj2[key]) {
        const isObj1Object = typeof obj1[key] === 'object';
        const isObj2Object = typeof obj2[key] === 'object';
        merged2[key] = {
            ...(
                isObj1Object
                    ? Object.values(obj1[key]).reduce((acc, v, i) => {
                        acc[Object.keys(obj2[key]).length + i] = v;
                        return acc;
                    }, {})
                    : (
                        isObj2Object
                            ? { [Object.keys(obj2[key]).length]: obj1[key] }
                            : { 0: obj1[key] }
                    )
            ),
            ...(
                isObj2Object
                    ? Object.values(obj2[key]).reduce((acc, v, i) => {
                        acc[Object.keys(obj1[key]).length + i] = v;
                        return acc;
                    }, {})
                    : (
                        isObj1Object
                            ? { [Object.keys(obj1[key]).length]: obj2[key] }
                            : { 1: obj2[key] })
            ),
        };
    } else if (obj1[key] || obj2[key]) {
        merged2[key] = obj1[key] || obj2[key];
    }
}

console.log(merged2);

您可以在此处测试不同的选项playground

如果您想在没有任何级别限制的情况下进行深度合并,则必须更新代码以使用递归方法。