JavaScript: Converting Array to Object

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

I am trying to convert an array to an object, and I'm almost there.

Here is my input array:

[ {id:1,name:"Paul"},   {id:2,name:"Joe"},   {id:3,name:"Adam"} ]

Here is my current output object:

{ '0': {id:1,name:"Paul"},   '1': {id:2,name:"Joe"},   '2': {id:3,name:"Adam"} }

Here is my desired output object:

[ {id:1,name:"Paul"},   {id:2,name:"Joe"},   {id:3,name:"Adam"} ] 

Here is my current code:

function toObject(arr) {   var rv = {};   for (var i = 0; i < arr.length; ++i)     if (arr[i] !== undefined) rv[i] = arr[i];   return rv; }

回答1:

You can't do that.

{ {id:1,name:"Paul"},   {id:2,name:"Joe"},   {id:3,name:"Adam"} } 

Is not a valid JavaScript object.

Objects in javascript are key-value pairs. See how you have id and then a colon and then a number? The key is id and the number is the value.

You would have no way to access the properties if you did this.

Here is the result from the Firefox console:

{ {id:1,name:"Paul"},   {id:2,name:"Joe"},   {id:3,name:"Adam"} }  SyntaxError: missing ; before statement


回答2:

Since the objects require a key/value pair, you could create an object with the ID as the key and name as the value:

function toObject(arr) {   var rv = {};   for (var i = 0; i < arr.length; ++i)     if (arr[i] !== undefined) rv[arr[i].id] = arr[i].name;   return rv; }

Output:

{     '1': 'Paul',     '2': 'Jod',     '3': 'Adam' }


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!