2

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

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.