Generate Separate Length for each object

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 forEach passes. Example: Marcelo > 0 Peter > 1 Lucas > 2

Every time the forEach passes I want the number to match the order, for example, if the marcelo is in the last it will be 2, and if Lucas stays in first it will be the 0

More or less like this:

B=0; B< obj.List.length ; B++
    
asked by anonymous 10.10.2017 / 07:49

1 answer

2

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

The possible parameters for forEach are:

(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);
    
10.10.2017 / 12:09