There are 2 parts to this question, one is how to rename the property and the other is how to do it for an arrangement.
Some different methods you can use ...
Current versions of Node.js (and modern browsers) implement Array.prototype.map that allows you to process an array and obtain a transformed result. This approach creates a new object with the new properties, it is for a structure -simple- as you used it. Of few fields.
var arreglo = [{
nombre: 'Luis',
apellido: 'Gonzales'
}, {
nombre: 'Maria',
apellido: 'Perez'
}, {
nombre: 'Ignacia',
apellido: 'Valdebenito'
}];
// para cada elemento, se crea un nuevo objeto con las nuevas propiedades.
var arreglado = arreglo.map( item => {
return { nombreUsuario: item.nombre , apellidoUsuario : item.apellido };
});
console.log(arreglado);
Care! 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 old browsers is very similar, you should change the function arrow for a normal declaration and use lodash.js or similar to have the function map .
Use of the operator delete
If you want to rename a single property (or a few), you can do something like this, taking advantage of the delete operator.
var arreglo = [{
nombre: 'Luis',
apellido: 'Gonzales'
}, {
nombre: 'Maria',
apellido: 'Perez'
}, {
nombre: 'Ignacia',
apellido: 'Valdebenito'
}];
// para cada elemento...
var arreglado = arreglo.map( item => {
// lo guardas temporalmente
var temporal = item.nombre;
// eliminas el valor que ya no quieres
delete item.nombre;
// creas el valor nuevo.
item.nombreNuevo = temporal;
return item;
});
console.log(arreglado);
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 site in English, it is proposed a method to rename the properties.
Object.prototype.renameProperty = function (oldName, newName) {
// no hacer nada si los nombre son iguales
if (oldName == newName) {
return this;
}
// Verificar si ya existe la propiedad con el nombre nuevo y evitar errores.
if (this.hasOwnProperty(oldName)) {
this[newName] = this[oldName];
delete this[oldName];
}
return this;
};
// lo usas así... también podrías usar map, o un for común..
// eso dependerá de la compatibilidad que necesites y lo
// "modernizado" que quieras que sea tu código.
for (var item of arreglo) {
item.renameProperty('nombre', 'nombreUsuario');
item.renameProperty('nombre', 'apellidoUsuario');
}