简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM