push object into array

46

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.

This question is tagged with javascript arrays object

~ Asked on 2016-10-25 21:36:33

The Best Answer is


87

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);

~ Answered on 2016-10-25 23:36:06


28

Create an array of object like this:

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

First you create the object inside of the push method and then return the newly created array.

~ Answered on 2017-07-10 11:31:06


Most Viewed Questions: