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);
-
1what is the error?Aravind– Aravind2016年08月29日 10:57:01 +00:00Commented Aug 29, 2016 at 10:57
-
There is no error, however the same object is being added in arrayRohit– Rohit2016年08月29日 11:27:43 +00:00Commented Aug 29, 2016 at 11:27
3 Answers 3
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
});
}
});
2 Comments
[] when creating new arrays.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.
Comments
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);
});