It is important to consider the specific needs of your data when choosing between using an array of objects or an object of arrays. Think about whether you will be performing more add/delete operations or read/find operations on the data, as this can influence your decision.
An array of objects makes it easier to add or delete entities with single atomic actions. For example:
var arr = [{x: 'a', y: 1}, {x: 'b', y: 2}];
arr.push({x: 'c', y: 3}); // add new entity
var obj = arr.shift(); // remove first element and store in variable
On the other hand, an object of arrays requires separate removal of elements like x
and y
:
var obj = {x: ['a', 'b'], y: [1, 2]};
// add
obj.x.push('c');
obj.y.push(3);
// remove
obj.x.shift();
obj.y.shift();
Object of arrays may be more compact when dealing with a lot of empty values, resulting in fewer bytes being sent over a network and less iterations needed for operations like finding min/max values.
var arr = [
{x: 'a'},
{y: 1},
{y: 2},
{y: 3},
{y: 4},
{y: 5},
{x: 'b', y: 6}
];
// Find max value for x property
var maxX = arr.reduce(function(max, obj) { // 7 iterations
return obj.x > max ? obj.x : max;
}, '')
The same operation with an object of arrays:
// more compact representation
var obj = {
x: ['a', 'b'],
y: [1, 2, 3, 4, 5, 6]
}
// fewer iterations (only 2 in this case)
var maxX = obj.x.reduce(function(max, val) {
return val > max ? val : max;
}, '')