javascript 合并两个具有相同关键帧的对象,但不重复

oyxsuwqo  于 2023-05-05  发布在  Java
关注(0)|答案(3)|浏览(170)

我有两个对象。我需要使用JavaScript合并它们。

let object1 = {
  fruits :[apple, orange],
  veggies:[carrot, pumpkin],
}

let object2 = {
  fruits :[apple, banana, mango],
  veggies:[potato, brinjal]
}

预期输出:

let object3 = {
  fruits : [apple,orange,banana,mango],
  veggies:[carrot,pumpkin,potato,brinjal]
}

我尝试的事情:

  1. object3 = {...object1, ...object2}
  2. const object3 = (obj1, obj2) => Object.assign({}, ...Object.keys(obj1).map(i => ({[i]:{...obj1[i], ...obj2[i]}}))); console.log(object3(object1, object2));
atmip9wb

atmip9wb1#

使用Set()和扩展运算符...

let object1 = {
  fruits :['apple', 'orange'],
  veggies:['carrot', 'pumpkin'],
}

let object2 = {
  fruits :['apple', 'banana', 'mango'],
  veggies:['potato', 'brinjal']
}

let object3 = {
  fruits: [...new Set([...object1.fruits, ...object2.fruits])],
  veggies: [...new Set([...object1.veggies, ...object2.veggies])],
}

console.log(object3);
5anewei6

5anewei62#

你的两次尝试都没有成功,因为:
1.这只合并析构的对象,而不合并内部的值
1.这是越来越接近,但它不做合并逻辑
试试这个:

let object1 = {
  fruits :['apple', 'orange'],
  veggies:['carrot', 'pumpkin'],
}

let object2 = {
  fruits :['apple', 'banana', 'mango'],
  veggies:['potato', 'brinjal']
}

function mergeObj(...objs) {
  const keys = objs.map(o => Object.keys(o)).flat();
  return keys.reduce((result, key) => {
    result[key] = [...new Set(objs.map(o => o[key]).flat())];
    return result;
  }, {});
}

console.log(mergeObj(object1, object2))
eblbsuwk

eblbsuwk3#

这是我代码

let object1 = {
  fruits :['apple', 'orange'],
   veggies:['carrot', 'pumpkin'],
 }

  let object2 = {
    fruits :['apple', 'banana', 'mango'],
   veggies:['potato', 'brinjal']
 }


 const Merge = (object1, object2) => {
 if (Array.isArray(object2)) {
    return [...object1, ...object2]
    } else {
    return Object.entries(object2).reduce((acc, [key, value]) => {
      if (
       Object.keys(acc).includes(key) &&
       typeof value === 'object'
      ) {
       acc[key] = Merge(acc[key], value)
      } else {
       acc[key] = value
      }
  
      return acc
    }, { ...object1 })
   }
 }

 const result = Merge(object1, object2);

 console.log(result);

相关问题