0

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

3
  • 1
    It depends of what you need to store. Array are good when ordering stuff. Object are good when you want to access directly to a property. For example: [{name: 'foo'}, {name: 'bar'}] is not really a good idea because looking for an object in the array is O(n) and you don't need order here Commented Dec 13, 2017 at 14:47
  • 1
    Depends on if you need an objects array or an object with an array property :p Commented Dec 13, 2017 at 14:49
  • Its like when to use bulletpoints in a table instead of table under bulletpoints Commented Dec 13, 2017 at 14:54

1 Answer 1

1

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;
}, '')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.