Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'}
]
like image 501
Devansh Avatar asked Dec 15 '25 18:12

Devansh


1 Answers

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; }
like image 63
Mohammad Usman Avatar answered Dec 17 '25 07:12

Mohammad Usman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!