Shadow
Shadow

Reputation: 13

JavaScript when to use arrayobject vs objectarray?

I am quite confused when should we declare object inside an array / array inside an object.

Object inside an array

var data = [{'Name': Alex,'Value': 2}]

Array inside an object

var data = {interest:['a','b','c'], name:['Ali','Baba','Alan']}

Can anyone help to explain this? thanks in advance

Upvotes: 0

Views: 96

Answers (1)

Vadim
Vadim

Reputation: 8779

Both representations are valid, but you should choose one according to what you are doing with this data afterwards. You should ask yourself: What kind of operations are more frequent: add/delete or read/find? The answer to this question may help you to choose.

With array of objects it is easier to add/delete entities, which may be done as single atomic action. Consider the following case:

var arr = [{x: 'a', y: 1}, {x: 'b', y: 2}];
arr.push({x: 'c', y: 3}); // add new to the end
var obj = arr.shift(); // remove first element of array and assign it to variable

With Object of arrays you will need to remove x and y separately:

var obj = {x: ['a', 'b'], y: [1, 2]};
// add
obj.x.push('c');
obj.y.push(3);
// remove
obj.x.shift();
obj.y.shift();

However, when you have a lot of empty values, object of arrays may have more compact representation (read: less bites to send over network) and less iterations to find something (like min/max).

var arr = [
  {x: 'a'},
  {y: 1},
  {y: 2},
  {y: 3},
  {y: 4},
  {y: 5},
  {x: 'b', y: 6}
];

// Find max of x
var maxX = arr.reduce(function(max, obj) { // 7 iterations
  return obj.x > max ? obj.x : max;
}, '')

The same with object of arrays:

// more compact
var obj = {
  x: ['a', 'b'],
  y: [1, 2, 3, 4, 5, 6]
}

// less iterations (only 2 in this case)
var maxX = obj.x.reduce(function(max, val) {
  return val > max ? val : max;
}, '')

Upvotes: 1

Related Questions