Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
}
share|improve this question
2  
Your desired output is an invalid json –  Ilan Frumer Jan 15 at 19:54
    
The desired format is not supportd in ECMA5, each object must have an identifier, like in your current output –  lexasss Jan 15 at 19:54
2  
The question is why do you need your data in such form? –  Ilan Frumer Jan 15 at 19:56
    
Just one question. Why ?:) –  Volodymyr Bilyachat Jan 15 at 19:57
2  
Your input and desired output is the same. –  making3 Jan 15 at 20:37
show 2 more comments

2 Answers

up vote 5 down vote accepted

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
share|improve this answer
    
sorry I updated my desired output format, please check now –  Paul Jan 15 at 20:35
add comment

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'
}
share|improve this answer
    
sorry I updated my desired output format, please check now –  Paul Jan 15 at 20:34
2  
@Paul now you're messing with us. Your input and output formats are identical! –  tkone Jan 16 at 2:22
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.