Home > Net >  combine two array with keys vertically in js
combine two array with keys vertically in js

Time:09-02

I have an array with keys name and type, I want to combine it with another array with key file, I tried using js method and even with map, not able to get anywhere, please help

array1-[{Name: '1', Type: 'type1'},{Name: '2', Type: 'type2'}]
array2-[{file:'one'},{file:'two'}              ]
combine-[{Name: '1', Type: 'type1',file:'one'},{Name: '2', Type: 'type2',file:'two'}]

CodePudding user response:

Loop through the arrays at the same time and use the "..." operator to add the properties of the objects.

let array1 = [{Name: '1', Type: 'type1'},{Name: '2', Type: 'type2'}]
let array2 = [{file:'one'},{file:'two'}]
let combined = []
for (let i = 0; i < array1.length && i < array2.length; i  ) {
  combined.push({...array1[i], ...array2[i]})
}
console.log(combined)

CodePudding user response:

this way...

const
  arr1 = [ { Name: '1', Type: 'type1' }, { Name: '2', Type: 'type2' } ] 
, arr2 = [ { file: 'one' }, { file: 'two' } ]
, combine = (arr2.length<arr1.length ? arr2 : arr1).map((x,i)=>({...arr1[i],...arr2[i]}))
  ;
console.log( combine )
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

you can also use Object.assign() method.

, combine = (arr2.length < arr1.length ? arr2 : arr1)
    .map((x,i)=>Object.assign( {}, arr1[i], arr2[i]) )
  • Related