I have this javascript objects:
var arr = [{id:'124',name:'qqq'}, 
           {id:'589',name:'www'}, 
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}]
I need to rename properties with name in arr1 to title:
var arr = [{id:'124',title:'qqq'}, 
           {id:'589',title:'www'}, 
           {id:'45',title:'eee'},
           {id:'567',title:'rrr'}]
What is elegant way to implement it in Javascript?
Use delete to remove a property from an object.
Use obj['newProperty'] to assign newProperty to an object.
var arr = [{id:'124',name:'qqq'}, 
           {id:'589',name:'www'}, 
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}];
           
arr.forEach( function(data) {
  data['title'] = data['name'];
  delete data['name'];
});
console.log(arr);
You can also use array#map
const arr = [{ id: '124', name: 'qqq' }, { id: '589', name: 'www' }, { id: '45', name: 'eee' }, { id: '567', name: 'rrr' } ],
      result = arr.map(({name, ...rest}) => ({...rest, title: name}));
console.log(result);
Use map :
var arr = [{
    id: '124',
    name: 'qqq'
  },
  {
    id: '589',
    name: 'www'
  },
  {
    id: '45',
    name: 'eee'
  },
  {
    id: '567',
    name: 'rrr'
  }
]
arr = arr.map((e) => {
  return {
    id: e.id,
    title: e.name
  }
});
console.log(arr);
it is not possible to change the name of property, but add a new one and delete the old one, i also got the code from somewhere dont remeber the exact source
function changeKey(originalKey, newKey, arr)
{
  var newArr = [];
  for(var i = 0; i < arr.length; i++)
  {
    var obj = arr[i];
    obj[newKey] = obj[originalKey];
    delete(obj[originalKey]);
    newArr.push(obj);
  }
  return newArr;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With