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
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
2 Answers
Reset to default 15Destructuring 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);
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]]))