Array of objects vs Object of Objects

后端 未结 6 1090
有刺的猬
有刺的猬 2020-12-13 05:56

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

JSON based:

\"users\": {
    \"id1\": {
        \"id\": \"id1\",         


        
6条回答
  •  伪装坚强ぢ
    2020-12-13 06:24

    You can use object[property] notation to access or set properties in an object in JavaScript.

    Go with array based approach at the backend, and convert the array to a map (JSON based as you refer to it) in the front end.

    var list = [{id: "id1", value: "One"}, {id: "id2", value: "Two"}]
    var map = {};
    list.forEach(function (item) { map[item.id] = item });
    map.get("id1")
    

    If your list changes, you can get the new list from backend and update your map in UI.

    This way your backend is faster to respond as it does not have to convert list to a map. Your front end will do a O(n) iteration once over the list to convert it to a map. But that is a small price compared to O(n) you will pay every time you search on a list.

    If you will be doing get by id predominantly on your data at the back end go with JSON Based at the backend itself (you can use LinkedHashMap to preserve order).

提交回复
热议问题