Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!