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

123
Visualizações
Transform a number to string inside an array of objects

Having the following input array:

  const input = [
    {
      id: 1,
      name: 1
    },
    {
      id: 2,
      name: 2
    },
    {
      id: 3,
      name: 3
    },
    {
      id: 4,
      name: 4
    }
  ];

it must be changed to

  output = [
    {
      id: 1,
      name: '1'
    },
    {
      id: 2,
      name: '2'
    },
    {
      id: 3,
      name: '3'
    },
    {
      id: 4,
      name: '4'
    }
  ];

so the value of name to be converted to string. I have found a method to do it but it seems like too complicated:

  const output = input.map((el) => ({
    ...el,
    name: el.name.toString()
  }));

Is there a better way to do this?

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

0

Using destructuring and String.

Check the differences with toString and String here What's the difference between String(value) vs value.toString()

const input = [
  {
    id: 1,
    name: 1,
  },
  {
    id: 2,
    name: 2,
  },
  {
    id: 3,
    name: 3,
  },
  {
    id: 4,
    name: 4,
  },
];

const output = input.map(({ name, ...rest }) => ({
  ...rest,
  name: String(name),
}));

console.log(output)

about 4 years ago · Juan Pablo Isaza Relatório

0

The solution you provided is perfectly fine and I don't think there is a better solution. Depending on whether you need to copy the array or not, you could use this solution, too:

input.forEach(el => el.name = el.name.toString());

This solution will modify the objects instead of creating new ones.

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