Insert the same value in a javascript array with push

0

I have the following situation, I am shaping an object within a for cycle and then inserting it into a array . The object is conforming me without problem, the detail I have it at the time I insert the data in the array, since when inserting the last record I change the previous ones and I put the last one in all the item Then I leave 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), …}
    
asked by Yoel Rodriguez 21.11.2018 в 02:47
source

1 answer

1

Your problem is solved by cleaning the object before re-inserting the values since you are not currently doing it, that's why you step on each value:

var data = [
  { value: 1, name: 'Uno' },
  { value: 2, name: 'Dos' },
  { value: 3, name: 'Tres' },
  { value: 4, name: 'Cuatro' }
]

var nuevoArreglo = [];
var dataObject = new Object();

for(i = 0; i < data.length; i++){
  dataObject = {};
  dataObject['value'] = data[i].value;
  dataObject['name'] = data[i].name;
  nuevoArreglo.push(dataObject);
}
console.log(nuevoArreglo);

You tell us how your colleague is going =)

    
answered by 21.11.2018 / 15:41
source