Search code examples
javascriptarraysobjectmultidimensional-arrayjavascript-objects

Nested array manipulation


I have below two array:

var val = [['aa', 'ab', 'ac'], ['bb', 'bc', 'bd']];
var key = ['item1', 'item2', 'item3'];

By using any javascript logic I want to get a new array in below format.

[
  {item1: 'aa', item2: 'ab', item3: 'ac'},
  {item1: 'bb', item2: 'bc', item3: 'bd'}
]

I tried using .forEach and .map() to achieve this, but somehow I couldn't able to do it.

Here is the sample code I tried.https://plnkr.co/edit/oKyjNsBu3wrRin7TaCIb?p=preview

var val = [['aa', 'ab', 'ac'], ['bb', 'bc', 'bd']];
var key = ['item1', 'item2', 'item3'];
var newArr = val.map((elm,i)=>{
  return {[key[i]]: elm[i]}
})
console.log('newArr', newArr);

I need the output as below.

[
  {item1: 'aa', item2: 'ab', item3: 'ac'},
  {item1: 'bb', item2: 'bc', item3: 'bd'}
]

Solution

  • You can use .map() and .reduce() methods to get the desired output:

    const vals = [['aa','ab','ac'],['bb','bc','bd']];
    const keys = ['item1','item2','item3'];
    
    const result = vals.map((val) => keys.reduce((r, c, i) => (r[c] = val[i], r), {}));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }