3

I'm trying to take an array of objects and, without mutating the original array, rename a specific key in each object.

I've created a new variable and assigned it to the result of using 'map' on my original array (to avoid mutation). Within the 'map' method, I've tried to deconstruct the 'keyToChange' parameter and spread the rest of the values to the 'newKey'.

const renameKeys = (array, keyToChange, newKey) => {
  const spreadArray = array.map(({keyToChange: newKey, ...rest}) => ({newKey, ...rest}));
    return spreadArray;
   };

The above code returns 'newKey: [undefined]' followed by the original array of objects.

Any help would be greatly appreciated.

3 Answers 3

4

You need a computed property name instead of a (not given) propery keyToChange.

const spreadArray = array.map(({ [keyToChange]: newKey, ...rest }) => ({ newKey, ...rest }));
//                               ^^^^^^^^^^^^^
Sign up to request clarification or add additional context in comments.

Comments

3

Use square brackets notation if you want to use dynamic value as key. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors */

 const spreadArray = array.map(({ [keyToChange]: newKey, ...rest}) => ({newKey, ...rest}));

Comments

2

If you want a an expression to be the key to be changed then use square brackets around it []

const renameKeys = (array, keyToChange, newKey) => {
  const spreadArray = array.map(({[keyToChange]: newKey, ...rest}) => ({newKey, ...rest}));
    return spreadArray;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.