jskidd3
jskidd3

Reputation: 4783

When should I use an object over an array and vice versa?

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?

Upvotes: 3

Views: 189

Answers (3)

Ken
Ken

Reputation: 548

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.

Upvotes: 3

LoremIpsum
LoremIpsum

Reputation: 4428

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.

Upvotes: 2

Bojangles
Bojangles

Reputation: 101543

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.

Upvotes: 8

Related Questions