0

I Have some array like below:

[
  [
    'James',
     23,
     'male'
  ],
  [
     'Britney',
     45,
     'female'
  ]
]

I would like to turn that into a json looking like:

[
{
    'name': 'James',
     'age': 23,
     'gender'': 'male'
},
{
    'name': 'Britney',
     'age': 45,
     'gender'': 'female'
}
]

I understand the json stringify part to convert the array to json but not sure how to create the keys for the values in an efficient way. Any help is greatly appreciated.

1
  • You can use the method suggested in this answer: arr.map(([name, age, gender]) => ({name, age, gender})); Commented Sep 5, 2020 at 15:42

2 Answers 2

1

Use map, then destruct the array and return an object.

const arr = [
  [
    'James',
    23,
    'male'
  ],
  [
    'Britney',
    45,
    'female'
  ]
]

const res = arr.map(([name, age, gender]) => ({
    name,
    age,
    gender
}))

console.log(res);

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

1 Comment

Perfect thanks that did it!! Appreciate the help.
0

You can do this with map with proper destructuring(for shortcut):

var a=[ [ 'James', 23, 'male' ], [ 'Britney',45,'female']];

var result = a.map(([name,age,gender])=>({name, age, gender}));

console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.