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
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' }