Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
Add element conditional between group of objects

I have the following code, to make a new array.

const datos = [{
        "id": "re_alt_sr",
        "quantity": 345,
        "selectable": false
      },
      {
        "id": "re_alt_gen",
        "quantity": 740,
        "selectable": true
      },
      {
        "id": "re2_alw_gen2",
        "quantity": 40,
        "selectable": true
      },
      {
        "id": "re_st_w_show",
        "quantity": 1,
        "selectable": true
      }]
var list = [];
for (const item of datos) {
  list.push({
    name: item.id,
    value: item.quantity,
    is: item.selectable
  })
}

console.log(list)

But I want to add a new element among which are selectable.

{"name": "default", "value": 0, "status": true}

Leaving something like this:

[
    {"name": "re_alt_sr", "value": 345, "is": false },
    {"name": "re2_alw_gen2","value": 40,"is": true },
    {"name": "default", "value": 0, "status": true},
    {"name": "re_alt_gen", "value": 740, "is": true},
    {"name": "default", "value": 0, "status": true},
    {"name": "re_st_w_show", "value": 1, "is": true}
]

Point to clarify: as you think: unselectables are one group and SI-selectables is another. There will be other arrays that are all "unselectable" so you don't need to add anything to them.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This SOLUTION stays close to your existing code by employing an if statement to get the "new element between those that are not selectable and those that are.".

Essentially what it does is keep track of the previous item's selectable state, and when a difference is detected, it inserts the new element.

const datos = [{
        "id": "re_alt_sr",
        "quantity": 345,
        "selectable": false
      },
      {
        "id": "re_alt_gen",
        "quantity": 740,
        "selectable": true
      },
      {
        "id": "re_st_w_show",
        "quantity": 1,
        "selectable": true
      }]
var list = [];

// Var to track of previous item's selectable state
var previousSelectableState = null; 

for (const item of datos) {
    
    
    // NEW CODE BEGIN
    if ( previousSelectableState !== null) {
        // Not at first item    
        
        if (previousSelectableState !== item.selectable ) {
            // Previous item selectable differs from this one
        
            list.push( {"id": "default", "quantity": 0, "status": true} );
        }
    }
    
    previousSelectableState = item.selectable; // for next iteration
    // NEW CODE END
    
    list.push({
        name: item.id,
        value: item.quantity,
        is: item.selectable
    })

}

console.log(list)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use .reduce(), which is a useful function that iterates through an array, and passes a value from each iteration to the next.

const datos = [{"id": "re_alt_sr","quantity": 345,"selectable": false},{"id": "re_alt_gen","quantity": 740,"selectable": true},{"id": "re_st_w_show","quantity": 1,"selectable": true}];

const list = datos.reduce((acc, val) => {
  // Can't use index here because we may have already 
  // injected extra items into array. So we use length instead
  const prev = acc[acc.length - 1];
  return prev && prev.selectable !== val.selectable ?
    [
      ...acc,
      {"id": "default", "quantity": 0, "status": true},
      val
    ] : 
    [...acc, val];
},[]);

console.log(list)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda