Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array to object with custom keys in JavaScript

I have array which I want to convert to object . Like ['jonas','0302323','[email protected]]. 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:[email protected]}. I am beginner to JS could somone please help me

like image 253
React Guy Avatar asked Oct 24 '25 15:10

React Guy


2 Answers

Destructuring makes this easy:

const yourArray = ['Jimbo', '555-555-5555', '[email protected]'];

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', '[email protected]'],
  ['Lakshmi', '123-456-7890', '[email protected]']
];

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

console.log(peopleObjects);
like image 145
Jacob Avatar answered Oct 26 '25 04:10

Jacob


Another solution is to use Object.fromEntries - link

const keys = ['name', 'phone', 'email'];
const values = ['jonas','0302323','[email protected]'];

const result = Object.fromEntries(keys.map((key, index) => [key, values[index]]))
like image 29
james Avatar answered Oct 26 '25 04:10

james



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!