-1

I'm trying to mangle data returned from an api. I've got an array of objects returned. I want to delete the password field and then add a couple of additional fields. I'd like to use the spread operator but my process feels a bit clunky.

myArray.map( item => {
    const newItem = { ...item };
    delete newItem.password;
    newItem.saved = true;
    return newItem;
});

Is there a nicer way to do this?

Aidan Ewen
  • 13,049
  • 8
  • 63
  • 88

1 Answers1

0

Given an array of objects -

const myArrayOfObjects = [
    {id: 1, keyToDelete: 'nonsense'},
    {id: 2, keyToDelete: 'rubbish'}
];

Delete the attribute keyToDelete, and add a new key newKey with the value "someVar".

myArrayOfObjects.map(({ keyToDelete, ...item}) => { ...item, newKey:'someVar'});

Updating the array to

[
    {id: 1, newKey:'someVar'},
    {id: 2, newKey:'someVar'}
]

See this great post for more information on the deletion method.

Aidan Ewen
  • 13,049
  • 8
  • 63
  • 88