1

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?

user842225
  • 5,445
  • 15
  • 69
  • 119
  • 1
    You can add a `delete el.name` after adding the new key. If you don't want to mutate the original array, `let newData = data.map(({ name: title }) => ({ title }))` – adiga Feb 17 '21 at 17:52

1 Answers1

2

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)
prasanth
  • 22,145
  • 4
  • 29
  • 53