6

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?

Michael
  • 13,950
  • 57
  • 145
  • 288

5 Answers5

14

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);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
5

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);
Serge K.
  • 5,303
  • 1
  • 20
  • 27
2
arr.map(e => { return { id: e.id, title: e.name }});
simon
  • 1,095
  • 6
  • 11
  • 3
    I'd recommen to add some comment to your answer. Without it, it may be not obvious that, for instance, if some object has an extra property (say, "date"), your solution will cause its "deletion" in the array. – YakovL Jul 07 '17 at 09:53
  • @MarceloGondim map does not modify the original array, you either have to reassign arr to the result of this, or you have to assign it to a new variable. – simon May 28 '20 at 07:41
2

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;
}
Sameer
  • 705
  • 10
  • 25
0

Here's how you delete key and value and assign to new key:

var arr = [{id:'124',name:'qqq'}, 
           {id:'589',name:'www'}, 
           {id:'45',name:'eee'},
           {id:'567',name:'rrr'}]
           
arr.forEach(function(o) {
    Object.defineProperty(o, 'title',
        Object.getOwnPropertyDescriptor(o, 'name'));
    delete o['name'];
});           
console.log(arr);
YakovL
  • 7,557
  • 12
  • 62
  • 102
Durga
  • 15,263
  • 2
  • 28
  • 52