最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert Array to object with custom keys in JavaScript - Stack Overflow

programmeradmin0浏览0评论

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

Share Improve this question asked Oct 29, 2020 at 0:17 React GuyReact Guy 991 gold badge1 silver badge7 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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);

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]]))
发布评论

评论列表(0)

  1. 暂无评论