Array of objects vs Object of Objects

me_digvijay picture me_digvijay · Jul 17, 2015 · Viewed 16.6k times · Source

The issue is to decided the trade offs between following notations:

JSON based:

"users": {
    "id1": {
        "id": "id1",
        "firstname": "firstname1",
        "lastname": "lastname1"
    },
    "id2": {
        "id": "id2",
        "firstaame": "firstname2",
        "lastname": "lastname2"
    }
}

Array Based:

users: [
    {
        "id": "id",
        "key2": "value2",
        "key3": "value3"
    },
    {
        "id": "id",
        "key2": "value2",
        "key3": "value3"
    }
]

Relating to this post on the same issue, I have decided (on front end) to use the JSON object notation instead of array of objects as it suits my requirements and better performance and less code in the browser.

But the problem is that the list itself is not static. By this I mean the list is being generated i.e. fetched/stored from DB (NoSQL) and created for new entries through a Java API at the server. I am not able to decide on which notation should I use at the back end (which eventually will also affect the UI too).

Any thoughts/suggestion about performance, maintainability or scalability is appreciated.

Answer

Naman Gala picture Naman Gala · Jul 17, 2015

It is a total opinion based question. There might be many other points, but I can point out as below.

JSON based approach : If I am not wrong then this will be implemented using Map on server side.

Advantage : In JavaScript you can directly use users.id1, users.id2 i.e. no need of iteration

Disadvantage : On client side, some how you will require the ids present in your JSON i.e. either hard coding it or using some dynamic approach which will tell you which id is present in your JSON.


Array Based approach : If I am not wrong then this will be implemented using Array/List on server side.

Advantage:

  1. On client side, you can directly iterate through array, without worrying in advance about which id is present inside it i.e. no hard coding.
  2. As pointed out by @JBNizet, array based approach will maintain the order.

Disadvantage : If you want to fetch single id then you will need to iterate through the array.

Generally we don't send much information on client side, so array based approach will not create any problem. And transforming array into map is possible on both the side (server and client) if you want id based approach.