按值合并对象,保持数组中的唯一值

时间:2018-02-13 00:41:51

标签: javascript arrays object

我一直在尝试做以下事情。我很难找到一个干净的解决方案:



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并且无法想出办法。任何帮助将不胜感激!

5 个答案:

答案 0 :(得分:2)

您可以使用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
}

资源

答案 1 :(得分:2)

您可以使用mergeWith方法并将空对象作为第一个参数传递以创建新对象。然后,您可以检查第一个属性的值是否等于秒,并基于该创建数组。



const obj1 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE1"
}

const obj2 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE2"
}

const result = _.mergeWith({}, obj1, obj2, function(a, b) {
  if (a === undefined) return b
  if (a != b) return [].concat(a, b)
})

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

您可以使用key循环遍历对象的for...in以检查值是否相等。请尝试以下方法:

&#13;
&#13;
var obj1 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE1"
}

var obj2 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE2"
}
var res={};
for(var key in obj1){
  if(obj1[key] == obj2[key]){
   res[key] = obj1[key];
  }
  else{
    var temp = []; temp.push(obj1[key]); temp.push(obj2[key]);
    res[key] = temp;
  }
}

console.log(res)
&#13;
&#13;
&#13;

答案 3 :(得分:0)

Object.keys(obj1).reduce(function (ack, key) {
    ack[o1key] = (obj1[key] === obj2[key]) 
        ? obj1[key]
        : [obj1[key], obj2[key]];
    return ack;
}, {})

答案 4 :(得分:0)

对于那个特定的例子

res = {}

for(i in obj1){
  res[i] = (obj2[i] != obj1[i])? [obj1[i], obj2[i]] :  obj1[i]
}