user2837851
user2837851

Reputation: 1191

javascript set property in array

I want to set the property(p1) of an item in an array. For example, array[1].p1="David". But an error happened. Following is the code, could someone give me a hint?Many thanks.

    var array1=new Array();         

        array1[0].p1="MARY";
        array1[1].p1="JHON";
        for (index = 0; index < array1.length; ++index) {
            alert(array1[index].p1);            
        }       

I`ve tried array1.push({p1:"MARY"}), it works! But it can not set the value by "particular" index.

Upvotes: 0

Views: 4328

Answers (4)

Mr.G
Mr.G

Reputation: 3559

myObject["123"] = { "C": 123, "D": 456 }; 

does not add more elements to the object (associative array), it replaces them; to add elements you'd have to write:

myObject["123"].C =123;
myObject["123"].D = 456;

As for #2 and #3, Javascript objects do not guarantee to return properties in the order in which they were added; for this you would have to resort to an array, and then after adjusting your data to the strictures of the different data structure, you could get the first element with:

myArray.shift()

Upvotes: 1

Andy
Andy

Reputation: 63524

What you are trying to do in your first example is add a property to an non-existent object in the first element slot of the array. This is why there's an error.

This is why your second example works. The object {p1:"MARY"} itself is being pushed into the first position. As Jon says in the comments this can also be done using array1[0] = {p1: "MARY"}.

(In your example, make sure you var your loop variables):

var array1 = new Array();
array1[0] = {p1: 'MARY'};
array1[1] = {p1: "JHON"};

for (var index = 0; index < array1.length; ++index) {
  console.log(array1[index].p1); // MARY, JHON
}

Fiddle

Upvotes: 1

AbstractProblemFactory
AbstractProblemFactory

Reputation: 9811

You asssumed that array is filled with empty objects {} by default which is not true. Before array1[0].properties you must place there object (hashmap): array1[0] = {}.

Upvotes: 2

simply-put
simply-put

Reputation: 1088

Array should be declared as an object

for e.g. a[0] = {"p1":"Mary"}

Upvotes: 1

Related Questions