JavaScript的:数组转换到对象 [英] JavaScript: Converting Array to Object
问题描述
我想一个数组转换为一个对象,我几乎没有。
下面是我输入数组:
[{ID:1,名称:保罗},
{ID:2,名称:乔},
{ID:3,名称:亚当}]
下面是我目前的输出对象:
{0:{ID:1,名称:保罗},
1:{ID:2,名称:乔},
2:{ID:3,名称:亚当}}
这是我想要的输出对象:
[{ID:1,名称:保罗},
{ID:2,名称:乔},
{ID:3,名称:亚当}]
下面是我目前的code:
函数toObject(ARR){
VAR RV = {};
对于(VAR I = 0; I< arr.length ++ I)
如果(ARR [I] ==未定义!)RV [I] =改编[I]
返回rv;
}
您不能这样做。
{{ID:1,名称:保罗},
{ID:2,名称:乔},
{ID:3,名称:亚当}}
是不是有效的JavaScript对象。
JavaScript中的对象是键 - 值对。看你怎么有 ID
,然后一个冒号,然后是多少?在键
是 ID
和数量是值
。
您没有任何办法,如果你这样做是为了访问属性。
下面是Firefox的控制台结果:
{{ID:1,名称:保罗},
{ID:2,名称:乔},
{ID:3,名称:亚当}}
语法错误:缺少;语句之前
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.
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
这篇关于JavaScript的:数组转换到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!