JavaScript:将数组转换为对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21146895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: Converting Array to Object
提问by Paul
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;
}
回答by tkone
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. See how you have id
and then a colon and then a number? The key
is id
and the number is the value
.
JavaScript 中的对象是键值对。看看你怎么有id
一个冒号,然后是一个数字?的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
回答by matth
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'
}