Devansh
Devansh

Reputation: 193

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'}
]

Upvotes: 2

Views: 126

Answers (3)

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

Using Object.fromEntries():

const values = [['aa','ab','ac'],['bb','bc','bd']];
const keys = ['item1','item2','item3'];

const result = values.map(v => Object.fromEntries(keys.map((k, i) => [k, v[i]])));

console.log(result);

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370759

Map the val array (change its name to allVals for better clarity) to objects using Object.fromEntries:

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

const output = allVals.map(vals => Object.fromEntries(
  vals.map((val, i) => [keys[i], val])
));

console.log(output);

Upvotes: 3

Mohammad Usman
Mohammad Usman

Reputation: 39322

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; }

Upvotes: 4

Related Questions