Converting an array of objects to a nested object

44 Views Asked by At

I've searched stack overflow quite a lot but cannot get the information needed, hence the question.

As jsonapi expects all the information to be in the form of objects.

I want to convert :

[{"id":2,"quantity":2},{"id":1,"quantity":2}]

to

{"0" : {"id":2,"quantity":2}, "1" : {"id":1,"quantity":2}}

Solution: If anyone needs help and doesn't want to get down voted for merely asking a question out of confusion.

function toObject(arr) {
      var obj = {};
      for (var i = 0; i < arr.length; ++i)
        if (arr[i] !== undefined) obj[i] = arr[i];
      return obj;
    }
1

There are 1 best solutions below

1
John Pink On BEST ANSWER

The object you desire isn't valid. All JSON objects work by key,value pair hence this wouldn't work :

{
    {"id":2,"quantity":2},
    {"id":1,"quantity":2}
}

Because you don't have any keys in the root object. You could do this though :

{
    "key1": {"id":2,"quantity":2},
    "key2": {"id":1,"quantity":2}
}

Does the difference seem clear to you ?