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

112
Visualizações
JS - Conditionally pushing items in nested object

I have this array:

let mainArray = [
  {
    "key1": "value1"     //           <------------
  },                     //                       |
  {                      //                       |
    "key2": "value2"     //                       |  key1 exists two times
  },                     //                       | 
  {                      //                       |
    "key1": "toAddValue" //           <------------
  }
]; 

Expected Output:

Key1 value should be in a Single array

[
    {
        'item': {
            'data': ['value1', 'toAddValue'], //  <-- It's values should be in Single arr
            'path': 'key1'    //                  <-- It's key name in path field.
        }
    },
    {
        'item': {
            'data': ['value2'],               // <-- its' value occurs once
            'path': 'key2'                    // <-- so it should be in one array.
        }
    }
]

Question:

If any of the key of mainArray is re-occurring / Repeating then, it should be added into single array called data

How do I do this?

var secondArray = []; // New array where all outputs are collected
let mainArray = [{
    "key1": "value1"
  },
  {
    "key2": "value2"
  },
  {
    "key1": "newKeyVal"
  }
];


for (let i = 0; i <= mainArray.length; i++) {
  for (let j = 0; j <= secondArray.length; j++) {

    if (secondArray.length == 0) {
      secondArray.push({
        "item": {
          'data': [Object.values(i)[0]],
          'path': `${Object.keys(i)[0]}`
        }
      })
    }
    if (secondArray[j].item.path === Object.keys(i)[0]) {
      secondArray[j].item.data.push([Object.values(i)[0]])
    }
  }
}
console.log(secondaryArray)

about 4 years ago · Juan Pablo Isaza
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