Home > front end >  Transform a number to string inside an array of objects
Transform a number to string inside an array of objects

Time:02-27

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?

CodePudding user response:

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)

CodePudding user response:

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.

  • Related