简体   繁体   中英

Converting an array of objects to a nested object

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

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 ?

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