I have the following situation, I am creating an object within a for loop and then inserting it into an array . The object is conforming to me without problem, I have the detail at the time I insert the data in the array, since when inserting the last record it changes the previous ones and places the last one in all the items . Here is the code to see if you can help me.
Thanks.
My code:
let arrayval = _data.valdatos.split("~");
var datagrapharray = [];
var datagraphobj = new Object();
for(i=0; i < arrayval.length; i++){
linegrafph = arrayval[i].split("#");
datagraphobj["label"] = linegrafph[1];
datagraphobj["backgroundColor"] = linegrafph[2];
datagraphobj["borderColor"] = linegrafph[3];
datagraphobj["borderWidth"] = 1;
datagraphobj["data"] = linegrafph[0].split(",");
console.log(datagraphobj);
datagrapharray.push(datagraphobj);
}
console.log(datagrapharray);
My objects:
{label: "Objeto1", backgroundColor: " rgba(255,0,0,0.2)", borderColor: " rgba(255,0,0,1)", borderWidth: 1, data: Array(12)}
{label: "Objeto2", backgroundColor: " rgba(0,64,128,0.2)", borderColor: " rgba(0,64,128,1)", borderWidth: 1, data: Array(12)}
{label: "Objeto3", backgroundColor: " rgba(0,0,0,0.2)", borderColor: " rgba(0,0,0,1)", borderWidth: 1, data: Array(12)}
My array:
0: {label: "Objeto3", backgroundColor: " rgba(0,0,0,0.2)", borderColor: " rgba(0,0,0,1)", borderWidth: 1, data: Array(12), …}
1: {label: "Objeto3", backgroundColor: " rgba(0,0,0,0.2)", borderColor: " rgba(0,0,0,1)", borderWidth: 1, data: Array(12), …}
2: {label: "Objeto3", backgroundColor: " rgba(0,0,0,0.2)", borderColor: " rgba(0,0,0,1)", borderWidth: 1, data: Array(12), …}
Your problem is solved by clearing the object before re-inserting the values since you're currently not doing that, that's why you step on each value:
Let us know how it goes mate =)