Simple question, what is better? Please explain in 1-2 sentences why. I haven't much worked with JSON files but think in future I will do more often. So it's better to start with proper structure, instead of working some time and realize another structure would be better.
"id" as key:
{
"0": {
"name": "name1",
"bdate": "bdate1",
"mail": "mail1",
"sex": "sex1"
},
"1": {
"name": "name2",
"bdate": "bdate2",
"mail": "mail2",
"sex": "sex2"
},
"2": {
"name": "name3",
"bdate": "bdate3",
"mail": "mail3",
"sex": "sex3"
}
}
"id" in data:
[
{
"id":"0",
"name": "name1",
"bdate": "bdate1",
"mail": "mail1",
"sex": "sex1"
},
{
"id":"1",
"name": "name2",
"bdate": "bdate2",
"mail": "mail2",
"sex": "sex2"
},
{
"id":"2",
"name": "name3",
"bdate": "bdate3",
"mail": "mail3",
"sex": "sex3"
}
]
CodePudding user response:
Using an object indexed by ID will make it easier to look up objects if there will be circumstances in which you'll have the ID to find in advance. With that, using your first approach will let you find the object as easily as:
const personObj = allObjects[id]
If you used an array instead, you'd have to iterate over the whole array in order to find it:
const personObj = allObjects.find(
obj => obj.id === id
);
which is an order of magnitude slower (though, that's only relevant if the amount of data is quite large).
Of course, make sure an ID uniquely identifies one, and only one, object.
If the IDs happen to exactly correspond to their position in the array - as in this example - you could use the array instead and use allObjects[id]
- but that could create problems later if items ever get added or removed from the array.
CodePudding user response:
If you need to look up users by id, then having a map will certainly be quicker. In most cases where you will be looking up values using a key, a map will be the choice that gives the best performance and most straightforward coding.
If you are always having to get every user, then a list may be more convenient, but its easy to convert a map to a list when you need to.
Most languages have straightforward syntax that will allow you to create a list from a map and vice versa. The cost of conversion is much the same.
Don't forget that a list contains extra information.. ie order that is not available on a map. So if order is all important.. eg items in a queue or similar, then choose to use a list.