Very often I see data structures like this:
var settings = {
languages: [
{
language: 'English',
translation: 'English',
langCode: 'en',
flagCode: 'us'
},
{
...
}
]
};
Or this:
var settings = {
languages: [
{
'en' : {
language: 'English',
translation: 'English',
flagCode: 'us'
}
},
{
...
}
]
};
And this can go many levels deep (within an object there are often other arrays containing further objects)...
Adding arrays brings in another level of complexity when arrays have to be looped through to find a certain object, if we don't know its position in the array. But even if know its position it's still more complicated to use than using purely nested objects, where everything can easily be referred to, using dot notation. Like in this case:
var settings = {
languages: {
'en' : {
language: 'English',
translation: 'English',
flagCode: 'us'
},
'de' : {
...
}
}
};
So when is it a good idea to use arrays within objects and when not?
My simple answer
Use objects ({...}
) when you need a collection of key:value
pairs
Use arrays ([...]
) when you need a collection of objects
Other differences
arrays are ordered, objects are not
arrays are automatically indexed with numbers, objects require you to specify an index
arrays have a .length
property, objects do not
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments