Generate Separate Length for each object

Asked

Viewed 32 times

0

Hello, all right ?

How do I generate a corresponding number for each Object, example

{
    "api": "api",
    "List": [{
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Marcelo"
    }, {
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Pedro"
    }, {
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Lucas"
    }],
    "arq": "1",
    "paste": "2"
}

I want to generate a number for each name when the foreach goes through. Example: Marcelo > 0 Peter > 1 Luke > 2

Every time the foreach passes I want the number to match the order, for example, if the matchbook comes last it will be 2 , and if Lucas comes first it will be 0

Sort of like this:

B=0; B< obj.List.length ; B++
  • The .forEach it already gives you this. It’s called the array’s input and it’s the second argument of the method. Where do you want to use this?

1 answer

2


As @Sergio has already said forEach already supports the index, ie the position of each element in the array.

The possible parameters for the forEach sane:

(valorCorrente, indice, array)

Applying in your code would look like this:

const json = `{
    "api": "api",
    "List": [{
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Marcelo"
    }, {
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Pedro"
    }, {
        "tipo": "1",
        "data": "10/10/2017",
        "Hora": "11:38",
        "Size": "0",
        "Nome": "Lucas"
    }],
    "arq": "1",
    "paste": "2"
}`;

let objeto = JSON.parse(json);

objeto.List.forEach((valorCorrente, indice) => { //forEach com valor e indice

  //aqui dentro do forEach cria o numero em cada valor da lista. 
  //Chamei o campo de numero, mas pode ter o nome que quiser
  valorCorrente.numero = indice; 
});

console.log(objeto.List);

Browser other questions tagged

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