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

152
Visualizações
Add comma after object value in array

I am trying to get a result like the following in order to call a SQL query. It's an array of objects (each object with a key, that's going to be VALUE and a value. The value must be into single quotes with a comma at the end):

[
  { VALUE: 'A', },
  { VALUE: 'B', },
  { VALUE: 'C', },
  { VALUE: 'D', },
  { VALUE: 'E', },
  { VALUE: 'F' }
]

I've tried using a for function in which I add an object for each element in a list. This is the result I get:

Code:

    let arr = [];
    const len = reqBody.values.length;

    for (let i = 0; i < len; i++)
    {
        arr.push( { VALUE: reqBody.values[i] } )
    }

Result:

[
  { VALUE: 'A' },
  { VALUE: 'B' },
  { VALUE: 'C' },
  { VALUE: 'D' },
  { VALUE: 'E' },
  { VALUE: 'F' }
]

I've tried using a map arrow function with a join at the end of it in order to try to add the comma after each value (so for the second line of the result code would be something like: { VALUE: 'A', }) but I cant make it work since that returns an array of strings, not objects like the ones I need.

This is the code described above:

Code:

let arr = [];
const len = reqBody.values.length;

for (let i = 0; i < len; i++)
{
    arr.push(Object.values({ VALUE: reqBody.values[i] }).map(v => `{ VALUE: '${v}', }`).join(','))
}

Result:

[
  "{ VALUE: 'A', }",
  "{ VALUE: 'B', }",
  "{ VALUE: 'C', }",
  "{ VALUE: 'D', }",
  "{ VALUE: 'E', }",
  "{ VALUE: 'F', }",
]

Is there any way to cast that string in the map function to be an object?

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

0

You need to construct the entire thing as a concatenated string, not as an array.

let reqBody = {
  values: ['A', 'B', 'C']
};

let items = reqBody.values.map(v => `{ VALUE: '${v}', }`);
let result = '[\n  ' + items.join(',\n  ') + '\n]';
console.log(result);

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