javascriptarraysjsonobjectarray-push

How can I push an object into an array?


I know it's simple, but I don't get it.

I have this code:

// My object
const nieto = {
  label: "Title",
  value: "Ramones" 
}

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

If I do this I'll get a simple array:

["Title", "Ramones"]

I need to create the following:

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

How can I use push() to add the object into the nietos array?


Solution

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