Home > Enterprise >  How to merge two different array of object in JavaScript? Check below example
How to merge two different array of object in JavaScript? Check below example

Time:09-24

Input Arrays:

var array1 = [
  {
    PersonalID: '11',
    qusetionNumber: '1',
    value: 'Something'
  },
  {
    PersonalID: '12',
    qusetionNumber: '2',
    value: 'whatever'
  },
];

var array2 = [
  {
    uniqueId: '111'
  },
  {
    uniqueId: '222'
  },
];

Result:

var results = [
  {
    PersonalID: '11',
    qusetionNumber: '1',
    value: 'Something',
    uniqueId: '111'
  },
  {
    PersonalID: '12',
    qusetionNumber: '2',
    value: 'whatever',
    uniqueId: '222'
  },
];

CodePudding user response:

There are a few ways to do this, perhaps this is acceptable? Simply looping over the first array and using the index to select the correct object from the second array.

var array1 = [
  {
    PersonalID: '11',
    qusetionNumber: '1',
    value: 'Something'
  },
  {
    PersonalID: '12',
    qusetionNumber: '2',
    value: 'whatever'
  },
];

var array2 = [
  {
    uniqueId: '111'
  },
  {
    uniqueId: '222'
  },
];

var result = [];

array1.forEach((itm, idx, _)  => { 
  result.push({ ...itm, ...array2[idx] });
});

console.log(result)

CodePudding user response:

You can use Array.map() along with spread syntax (...) to merge the values from the two arrays.

const array1 = [ { PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2', value: 'whatever' }, ];
const array2 = [ { uniqueId: '111' }, { uniqueId: '222' }, ];

const result = array1.map((el, idx) => ({ ...el, ...array2[idx]}));   
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

var array1 = [
  {
    PersonalID: '11',
    qusetionNumber: '1',
    value: 'Something'
  },
  {
    PersonalID: '12',
    qusetionNumber: '2',
    value: 'whatever'
  },
];

var array2 = [
  {
    uniqueId: '111'
  },
  {
    uniqueId: '222'
  },
];
// if you don't want array1 to be modified use instead
// Array.from(array1).map(function(e,i){return Object.assign(e,array2[i])})
array1.map(function(e,i){return Object.assign(e,array2[i])})

console.log(array1)

CodePudding user response:

I can also use Object.assign

var array1 = [{
    PersonalID: '11',
    qusetionNumber: '1',
    value: 'Something'
  },
  {
    PersonalID: '12',
    qusetionNumber: '2',
    value: 'whatever'
  },
];

var array2 = [{
    uniqueId: '111'
  },
  {
    uniqueId: '222'
  },
];



let myArr = []
for(let i = 0 ; i<array1.length ; i  ){
myArr.push(Object.assign(array1[i], array2[i]))
}

console.log(myArr)

CodePudding user response:

In addition to the already provided approaches one also could implement callback functions for ...

  • a map based approach where the callback utilizes the map methods 2nd thisArg parameter for providing the 2nd array (the OP's array2).

  • a reduce based approach where the callback gets the 2nd array (the OP's array2) provided as property of the reduce methods 2nd parameter, its initial value.

In both cases Object.assign is one possible way of creating a merged object which is loosely decoupled from both of its source items.

Unlike all the other so far provided solutions both suggested ways have in common that each implementation is agnostic to the OP's outer-scope array-references. And due to being provided as function statements the code is re-usable as well.

const array1 = [{
  PersonalID: '11',
  qusetionNumber: '1',
  value: 'Something'
}, {
  PersonalID: '12',
  qusetionNumber: '2',
  value: 'whatever'
}];

const array2 = [{
  uniqueId: '111'
}, {
  uniqueId: '222'
}];


function mergeWithBoundArraysRelatedItem(item, idx) {
  return Object.assign({}, item, this[idx]);  
}
console.log(
  '`map` based ...\n\n',
  'array1.map(mergeWithBoundArraysRelatedItem, array2) =>',
  array1
    .map(mergeWithBoundArraysRelatedItem, array2)
);

function mergeRelatedArrayItems({ result, source }, item, idx) {
  result.push(
    Object.assign({}, item, source[idx])
  );
  return { result, source };
}
console.log(
  '`reduce` based ...\n\n',
  'array1.reduce(mergeRelatedArrayItems, { source: array2, result: [] }).result =>',
  array1
    .reduce(mergeRelatedArrayItems, {
      source: array2, result: [],
    })
    .result
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

CodePudding user response:

var array1 = [
  {
    PersonalID: '11',
    qusetionNumber: '1',
    value: 'Something'
  },
  {
    PersonalID: '12',
    qusetionNumber: '2',
    value: 'whatever'
  },
];

var array2 = [
  {
    uniqueId: '111'
  },
  {
    uniqueId: '222'
  },
];

const fun =(ar , ar2)=>{
  for(let [k , v] of Object.entries(ar2)){
    for(x in v){
      ar[k][x] = v[x]
}  
}
  return ar
}
console.log(fun(array1 , array2))

  • Related