Rohit
Rohit

Reputation: 7161

Adding object in javascript array at runtime

The mRegion object adds last object multiple times, however the objBeacon prints different objects. What is wrong with the mRegion?

      var mRegion = new Array();

      var objBeacon = {
          id: '10',
name:'name',   
          description: 'description'
      };
      $.ajax(settings).done(function(response) {
                  // populate beacon registry in an array
                  for (var i in response.items[0].devices) {
                      objBeacon.id = response.items[0].devices[i].id;
                      objBeacon.name = response.items[0].devices[i].name;
                      objBeacon.description = response.items[0].devices[i].description;


                      console.log("value of i is" + i);
                      console.log(objBeacon);

                      mRegion.push(objBeacon);
                  }
                  console.log(mRegion);

Upvotes: 1

Views: 248

Answers (3)

Michał Młoźniak
Michał Młoźniak

Reputation: 5556

Objects in javascript are passed by reference. You only have one variable objBeacon and each array element is pointing to this variable. Whenever you change objBeacon, all references will change.

var mRegion = [];

$.ajax(settings).done(function(response) {
  // populate beacon registry in an array
  for (var i in response.items[0].devices) {
    mRegion.push({
      id: response.items[0].devices[i].id,
      uid: '00',
      major: 1,
      minor: 1,
      name: response.items[0].devices[i].name,
      description: response.items[0].devices[i].description
    });
  }
});

Upvotes: 2

lippoliv
lippoliv

Reputation: 727

As you are using objects your using "references" instead of "clones".

That code should work (even it is not very beautifull)

var mRegion = new Array();


$.ajax(settings).done(function(response) {
    // populate beacon registry in an array
    for (var i in response.items[0].devices) {
        var objBeacon = {
            id: '10',
            uid: '00',
            major: 1,
            minor: 1,
            name: 'name',
            description: 'description'
        };

        objBeacon.id = response.items[0].devices[i].id;
        objBeacon.name = response.items[0].devices[i].name;
        objBeacon.description = response.items[0].devices[i].description;


        console.log("value of i is" + i);
        console.log(objBeacon);

        mRegion.push(objBeacon);
    }
    console.log(mRegion);
});

Upvotes: 0

Quentin
Quentin

Reputation: 944054

You only ever create one object and assign a reference to it to objBeacon.

Each time you go around the loop you modify the single object you have and push an additional reference to it into the array.

If you want an array of different objects, you need to create a new object each time you go around the loop.

Upvotes: 0

Related Questions