我一直在尝试执行以下操作。我很难提出一个干净的解决方案:
obj1 = {
key1: "ABC",
key2: "123",
key3: "UNIQUE1"
}
obj2 = {
key1: "ABC",
key2: "123",
key3: "UNIQUE2"
}
//I've been trying to merge these to look like the below output
obj3 = {
key1: "ABC",
key2: "123",
key3: ["UNIQUE1", "UNIQUE2"]
}
本质上,我想将每个键的唯一值保留在数组中。我也尝试过查看lodash,但还没有想出办法。任何帮助将非常感激!
最佳答案
您可以使用reduce
函数并在obj1
的键上循环
var obj1 = {
key1: "ABC",
key2: "123",
key3: "UNIQUE1",
key5: "4567",
key7: "y",
key8: "8y",
key9: "yi89",
key0: "dhdh64",
key12: "dhdh64",
key11: "dhdh64"
}
var obj2 = {
key1: "ABC",
key2: "123",
key3: "UNIQUE2",
key4: "1212",
key6: "a",
key7: "z",
key11: "z"
}
var result = Object.keys(obj1).reduce((a, k) => {
a[k] = obj2[k] === undefined || obj1[k] === obj2[k] ? obj1[k] : [obj1[k], obj2[k]];
return a;
}, { ...obj1, ...obj2 });
console.log(result);
.as-console-wrapper {
max-height: 100% !important
}
资源资源
Array.prototype.reduce()
关于javascript - 通过值合并对象,在数组中保留唯一值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48757824/