'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?
Solution 1:[1]
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)
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Siva K V |
| Solution 2 | nah0131 |
