What Reduce method is doing here

const rename_keys = (keysMap, obj) =>
  Object.keys(obj).reduce(
    (acc, key) => ({
      ...acc,
      ...{ [keysMap[key] || key]: obj[key] }
    }),
    {}
  );
const obj = { name: 'Bobo', job: 'Programmer', shoeSize: 100 };
console.log("Original Object");
console.log(obj);
console.log("-------------------------------------");
result = rename_keys({ name: 'firstName', job: 'Actor' }, obj);
console.log("New Object");
console.log(result);

What the following doing in the above code:

...acc,
      ...{ [keysMap[key] || key]: obj[key] }

You left out an important part, the curly braces:

{ ...acc, ...{ [keysMap[key] || key]: obj[key] } }

This means that you are creating an object. Do you know what the spread syntax (...) does? When used on an object it expands the key/value pairs in that object so they can be used to create a new object. In other words, it’s a convenient shortcut that allows you to take all of the key/value pairs in one object and put them into another object. So the above code is creating a new object by spreading out the object acc and combining that with the object created by { [keysMap[key] || key]: obj[key] } (again, by using spread syntax) .

As for { [keysMap[key] || key]: obj[key] }, this is just creating a simple object with one key/value pair. If [keysMap[key] is defined then that will be used as the key, otherwise key will be used. The value is just the value of obj[key].

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

1 Like