How to add list to a Javascript object

Asked

Viewed 59 times

1

I’ve been doing several tests for some time to be able to add a list to an object. I tried several ways and left the code in this format so that it is easier to understand the problem!

The code below returns me an object of this type: {nome: "matheus", produto: "caderno", values: {qtd: "7",valor1: "2.22",valor2: "2.22",valor3: "22.22"}}. Passing only the last object created in the intermediary variable I would like it to return me an object with the list in values in this format:

{nome: "matheus", produto: "caderno", values: 
[{qtd: "4",valor1: "1.00",valor2: "1.20",valor3: "11.20"},
{qtd: "5","valor1": "1.20",valor2: "1.03",valor3: "21.03"},
{qtd: "6",valor1: "1.22",valor2: "1.12",valor3: "2.22"},
{qtd: "7",valor1: "2.22",valor2: "2.22",valor3: "22.22"},
]}

I tried to add with the push did not work, I tried to put a list in the object and it did not work, I did several tests and nothing worked out follows below the code:

var object = new Object();

object.nome = "matheus";

object.produto= "caderno"

teste();
function teste() {

    let listQtd = ["4","5","6","7"]
    let listValor1 = ["1.00","1.20","1.22","2.22"]
    let listValor2 = ["1.20","1.03","1.12","2.22"]
    let listValor3 = ["11.20","21.03","31.12","22.22"]  

    let retList = new Object();

    for (let i = 0; i < listQtd.length; i++) {
        retList.qtd = listQtd[i];
        retList.valor1 = listValor1[i];
        retList.valor2 = listValor2[i];
        retList.valor3 = listValor3[i]

        // Aqui ele so adiciona o ultimo elemento preciso que adicione uma lista.
        object.values = retList
    }

    console.log(object)
}

1 answer

1


Just initialize the field value values with a array empty and use function push to increase it.

var object = new Object();

object.nome = "matheus";
object.produto = "caderno"
object.values = [];

teste();

function teste() {

  let listQtd = ["4", "5", "6", "7"]
  let listValor1 = ["1.00", "1.20", "1.22", "2.22"]
  let listValor2 = ["1.20", "1.03", "1.12", "2.22"]
  let listValor3 = ["11.20", "21.03", "31.12", "22.22"]

  for (let i = 0; i < listQtd.length; i++) {
    let retList = new Object();
    retList.qtd = listQtd[i];
    retList.valor1 = listValor1[i];
    retList.valor2 = listValor2[i];
    retList.valor3 = listValor3[i];

    object.values.push(retList);
  }

  console.log(object)
}

The operator = is attributable and not incremental, so your previous solution didn’t work out the way you wanted it to.

  • 1

    The solution caters thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.