Skip to content Skip to sidebar Skip to footer

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 ou

Solution 1:

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

Solution 2:

Since the objects require a key/value pair, you could create an object with the ID as the key and name as the value:

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

Post a Comment for "Javascript: Converting Array To Object"