3

I commonly use arrays to achieve tasks that might be better suited using objects. Rather than continuing to wonder if it would be better to use an object for a task, I've decided to pose the question on Stack Overflow.

array = ["James", 17];
object = {name:"James", age:17};

They both seem similar in syntax, and to me they seem to achieve the same thing when used. When should I use an an object over an array and vice versa? Are there general rules as to when I should use one over the other?

jskidd3
  • 4,609
  • 15
  • 63
  • 127
  • 1
    Have a look to http://stackoverflow.com/questions/688097/objects-vs-arrays-in-javascript-for-key-value-pairs – mguimard Jul 29 '13 at 14:44
  • Which task do you have in mind? If it's not converting to CSV, then objects are usually suited better. – Bergi Jul 29 '13 at 15:05

3 Answers3

8

Use an object when you want named keys (key:value pairs), otherwise use an array. You can even use array notation with objects:

object = {name:"James", age:17};
object['name'];    // James

In your case, it looks like you're storing information in fields about a person. Here, it makes perfect sense to use an object because the key identifies the type of data you're storing in each field. An array is for a simple list of data.

Bojangles
  • 99,427
  • 50
  • 170
  • 208
  • Thanks very much. This certainly seems like a better way as to my previous way of doing things which was setting constants for indexes. Objects seem to do that themselves. :D – jskidd3 Jul 29 '13 at 15:15
3

In your first example using the array, you're setting up a relationship between two indexes in that array. This is discouraged as your code has no inherent knowledge that you intend to associate one with the other. This is the perfect opportunity to use objects as in your second line.

Consider the opportunities to use them concurrently:

var match = {};

var peopleProps = {
    hair: ['brown', 'blonde', 'red'],
    eyes: ['brown', 'blue', 'green']
};

var person = {
   name: 'James',
   age: '17',
   hair: 'brown',
   eyes: 'blue'
};


for(var prop in person) {
    for(var subProp in peopleProps) {
      for(var i=0, l=peopleProps[subProp].length; i<l; i++) {
        if(prop == subProp && person[prop] === peopleProps[subProp][i]) {
          (match[prop][subProp])? match[prop][subProp]++ : match[prop][subProp] = 1;
        }
      }
    }
}

Here we can see the usefulness in using arrays to create mapping terms and objects to associate them.

Ken
  • 548
  • 6
  • 19
2

The point is : abstraction level. You'll want to modelize your data the way it is in "real life". An array is a list of items, an object is an item.

LoremIpsum
  • 4,328
  • 1
  • 15
  • 17