4

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 2

15

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

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

6 Comments

what if we have multiple array case Like [ [......],[..........] ]
Same concept. To convert an array of X to an array of Y, use its map function. Added an example.
one last thing please . In array I have string like [.... , .... , "data 1 , data 2 " ] . what I want to achieve actually make an array of object like [ ...... , ....... , items : [{name:data 1, phm:data2},......] Could you please help me
Sounds complicated, and it's not clear exactly what your input and output is. I'd suggest posting as a separate question.
|
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.