Rename a field in each object of a list

I have a list of object, each object has a field name:

let data = [{name: 'foo'}, {name: 'bar'}, {name: 'ipsum'}];

I would like to rename the name field to title. I tried following:

data.map(el => {el.title = el.name});

  console.log(`${JSON.stringify(data)}`);

However, the result is that each object has an additional field title instead of renaming name field to title. How can I rename the name field to title for each object in a list?

1 thought on “Rename a field in each object of a list”

  1. You need to create new array using Array#map with key of title

    let data = [{name: 'foo'}, {name: 'bar'}, {name: 'ipsum'}];
    
    let res = data.map(el => ({title:el.name}));
    
    console.log(res)
    Reply

Leave a Comment