pmirnd pmirnd - 1 month ago 7
Javascript Question

push object into array

I know it's simple, but I cant get it.

I have this code:

var nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);


label is some string like "Title" and value "Ramones". If I do this I'll get a simple array like

["Title", "Ramones"]


I need to create this:

[{"01":"Title", "02": "Ramones"}]


How can I do those push to the nietos array in order to push them as objects? the numbers 01, 02 will be generated with some i,k vars because all this is inside a for.

Answer

You have to create an object. Assign the values to the object. Then push it into the array:

var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);