[英]JavaScript: Converting Array to Object
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;
}
You can't do that. 你不能那样做。
{ {id:1,name:"Paul"},
{id:2,name:"Joe"},
{id:3,name:"Adam"} }
Is not a valid JavaScript object. 不是有效的JavaScript对象。
Objects in javascript are key-value pairs. javascript中的对象是键值对。 See how you have id
and then a colon and then a number? 看看您的id
如何,然后是冒号,然后是数字? The key
is id
and the number is the value
. key
是id
,数字是value
。
You would have no way to access the properties if you did this. 如果执行此操作,则将无法访问属性。
Here is the result from the Firefox console: 这是Firefox控制台的结果:
{ {id:1,name:"Paul"},
{id:2,name:"Joe"},
{id:3,name:"Adam"} }
SyntaxError: missing ; before statement
Since the objects require a key/value pair, you could create an object with the ID as the key and name as the value: 由于对象需要键/值对,因此可以创建一个以ID为键,名称为值的对象:
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'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.