0

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?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • To cast numbers to strings in javascript there are several ways, your way is good but if you want a shorter way you can use `number + ''` statement as in `output = input.map(x=>({id:x.id,name:name+''}))` – clay Feb 23 '22 at 17:33
  • `JSON.parse(JSON.stringify([{id:1,name:1},{id:2,name:2}]).replaceAll(/("name":)(\d+)/g,"$1\"$2\""))`, if you just want to see the world burn. – tevemadar Feb 23 '22 at 17:49

2 Answers2

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)
Siva K V
  • 10,561
  • 2
  • 16
  • 29
-1

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.

nah0131
  • 329
  • 1
  • 8
  • 1
    In the question the OP wants to create a new output object, you are modifying the original object ... – clay Feb 23 '22 at 17:39
  • I am aware that I am modifying the original object(s), that is why I explicitly stated that in my answer. – nah0131 Feb 23 '22 at 17:49