Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  32] [ 4]  / answers: 1 / hits: 10325  / 4 Years ago, thu, october 29, 2020, 12:00:00

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


More From » arrays

 Answers
26

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




[#2402] Saturday, October 24, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
paolam

Total Points: 437
Total Questions: 107
Total Answers: 106

Location: Aland Islands
Member since Wed, Nov 17, 2021
3 Years ago
paolam questions
Wed, Nov 20, 19, 00:00, 5 Years ago
Fri, Oct 18, 19, 00:00, 5 Years ago
;