Convert Array to object with custom keys in JavaScript

Viewed 4027

I have array which I want to convert to object . Like ['jonas','0302323','jonas84@gmail.com]. Now what I want to achieve I want to convert array into object and I want to assign custom keys into that object .

Expected Result : {name:'Jonas',phone:84394934,email:jonas84@gmail.com}. I am beginner to JS could somone please help me

1 Answers

Destructuring makes this easy:

const yourArray = ['Jimbo', '555-555-5555', 'jimbo@aol.com'];

const [name, phone, email] = yourArray;
const yourObject = { name, phone, email };

console.log(yourObject);

The first statement pulls items out of the array and assigns them to variables. The second statement creates a new Object with properties matching those variable names + values.

If you wanted to convert an Array of Arrays, simply use the same technique with map:

const peopleArrays = [
  ['Jimbo', '555-555-5555', 'jimbo@aol.com'],
  ['Lakshmi', '123-456-7890', 'lakshmi@compuserve.com']
];

const peopleObjects = peopleArrays
  .map(([name, phone, email]) => ({ name, phone, email }));

console.log(peopleObjects);

Related