Home > Net >  How to merge two array of object into one array of object based on key?
How to merge two array of object into one array of object based on key?

Time:12-01

i'm trying to merge two array of object based on key. two array of object like this,

    let array1 = [
    {
      name: "Deepak",
      age: 20
    },
    {
      name: "John",
      age: 30
    }
    ]
    let array2 = [
    {
      name: "Deepak",
      favGame: "Cricket"
    },
    {
      name: "John",
      favGame: "Football"
    },
    {
      name: "Kailash",
      favGame: "Basketball"
    }
   ]

I found difficulties to merge as expected format. I expecting format like this

   let finalArray = [
    {
        name: "Deepak",
        age: 20,
        favGame: "Cricket"
      },
      {
        name: "John",
        age: 30,
        favGame: "Football"
      },
      {
        name: "Kailash",
        favGame: "Basketball"
      }
    ]

CodePudding user response:

let a1 = [ { name: 'Deepak', age: 20 }, { name: 'John', age: 30 } ]
let a2 = [
  { name: 'Deepak', favGame: 'Cricket' },
  { name: 'John', favGame: 'Football' },
  { name: 'Kailash', favGame: 'Basketball' }
]

console.log(Object.values([...a1, ...a2]
  .reduce((a,{name, ...p})=>(a[name]={...a[name]??{},name,...p},a), {})))

CodePudding user response:

Using Array.map() and Array.find() can do it

let array1 = [
    {
      name: "Deepak",
      age: 20
    },
    {
      name: "John",
      age: 30
    }
    ]

let array2 = [
    {
      name: "Deepak",
      favGame: "Cricket"
    },
    {
      name: "John",
      favGame: "Football"
    },
    {
      name: "Kailash",
      favGame: "Basketball"
    }
   ]
   
let result = array2.map(a => {
   let obj = array1.find(i => i.name === a.name)
   if(obj){
    a.age = obj.age
   }
   return a
})
console.log(result)

CodePudding user response:

You can do it like this:

const array1 = [
  {
   name: "Deepak",
   age: 20
  },
  {
   name: "John",
   age: 30
  }
];

const array2 = [
  {
   name: "Deepak",
   favGame: "Cricket"
  },
  {
   name: "John",
   favGame: "Football"
  },
  {
   name: "Kailash",
   favGame: "Basketball"
  }
];

const mergedArray = [...array1, ...array2];
const newArray = [];
mergedArray.forEach((item) => {
  const key = item.name;
  let index = -1;
  newArray.forEach((newArrayItem, _index) => {
    if(newArrayItem.name === key)
    index = _index;
  });
  if(index === -1){
    newArray.push({});
    index = newArray.length - 1;
  }
  newArray[index]["name"] = item.name;
  if(item.age) {
    newArray[index]["age"] = item.age;
  }
  if(item.favGame) {
    newArray[index]["favGame"] = item.favGame;
  }
});
console.log(newArray);

  • Related