-3

I'm training with using Javascript objects, and I found these examples of representing Javascript arrays:

var obj = {
    key : {
        0 : {name : "test0"},
        1 : {name : "test1"},
        2 : {name : "test2"}
    }
}

var obj2 = {
    key : [
        {name : "test0"},
        {name : "test1"},
        {name : "test2"}
    ]
}

console.log(obj.key[0].name);  //test0
console.log(obj2.key[0].name); //test0

Which of these is the appropriate representation of an array? Are these equivalent, and why?

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
Jax Teller
  • 1,447
  • 2
  • 15
  • 24
  • 2nd is better as it represents in JSON format. try studying http://www.w3schools.com/js/js_objects.asp and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects – Deepak Sharma Jun 27 '16 at 12:41

2 Answers2

0

The second example is the better solution, particularly if you're planning to treat the object as an array:

var obj2 = {
    key: [
        {name: "test0"},
        {name: "test1"},
        {name: "test2"}
    ]
};

This will allow you to access the elements sequentially:

for (var i = 0; i < obj2.length; ++i) {
    console.log("Name: ", obj2[i].name);
}

The other (first) example will create an object with numeric keys, but that does not actually create an array. Given that, array methods will not be available on the object.

However, if you're trying to create a sparse array, this is the appropriate approach. Consider this example:

var obj = {
    key : {
        0 : {name : "test0"},
        3 : {name : "test3"},
        8 : {name : "test8"}
    }
}

This will give you an object that can be indexed by an integer, but the integer indexes don't have to be contiguous. In fact, the example above that iterates the array will fail in this case, and instead, you should use this approach:

for (var i in obj2) {
    console.log("Name: ", obj2[i].name);
}
Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
-2
var obj2 = {
    key: [
        {name: "test0"},
        {name: "test1"},
        {name: "test2"}
    ]
};

This is best way and the correct way .Easier to iterate .Array of objects is the recommended as against marking keys with 0,1,2,3,4

Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
  • This is not the "correct JSON notation" because it is not JSON. http://stackoverflow.com/questions/3975859/what-are-the-differences-between-json-and-javascript-object – CherryDT Jun 27 '16 at 12:40
  • I agree my point is about array of objects I will change it Plz upvote – Piyush.kapoor Jun 27 '16 at 12:41