I need to rename a Json property from an array
[
{
nombre : 'Luis',
apellido : 'Gonzales'
},
{
nombre : 'Maria',
apellido : 'Perez'
},
{
nombre : 'Ignacia',
apellido : 'Valdebenito'
}
]
and I need to modify it as follows
[
{
nombreUsuario : 'Luis',
apellidoUsuario : 'Gonzales'
},
{
nombreUsuario : 'Maria',
apellidoUsuario : 'Perez'
},
{
nombreUsuario : 'Ignacia',
apellidoUsuario : 'Valdebenito'
}
]
Is it possible to do it through a function and not do it through a loop for
that goes through the array to enter it in another?
There are 2 parts to this question, one is how to rename the property and the other is how to do it for an array.
Some different methods you can use...
Current versions of Node.js (and modern browsers) implement Array.prototype.map which allows you to process an array and get a transformed result. This approach creates a new object with the new properties, it is for a -simple- structure as you used. Few fields.
Watch out! This syntax will not work in old versions of node 3.x, nor in old browsers. If you need to do it for node 3.x or older browsers it's very similar, you should change the arrow function to a normal declaration and use lodash.js or similar to have the map function .
Using the delete operator
If you want to rename a single property (or a few), you can do something like this, taking advantage of the delete operator.
Of course you can do it with a for, either by creating an obj or using delete, but map is more idiomatic .
Finally for the old school, in this answer from the English site, a method for renaming properties is proposed.