w3resource

JavaScript: Create an object with the same keys as the provided object and values generated by running the provided function for each value

JavaScript fundamental (ES6 Syntax): Exercise-84 with Solution

Write a JavaScript program to create an object with the same keys as the provided object. It will also generate values generated by running the provided function for each value.

Maps the values of an object using the provided function, generating a new object with the same keys.

  • Use Object.keys() to iterate over the object's keys.
  • Use Array.prototype.reduce() to create a new object with the same keys and mapped values using fn.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2
// Define the function 'mapValues' to map each value of an object to a new value using a given function.
const mapValues = (obj, fn) =>
  // Reduce the object's keys, apply the function to each value along with its key, and store the resulting values in a new object.
  Object.keys(obj).reduce((acc, k) => {
    acc[k] = fn(obj[k], k, obj);
    return acc;
  }, {});

// Example usage:
const users = {
  fred: { user: 'fred', age: 40 },
  pebbles: { user: 'pebbles', age: 1 }
};
console.log(mapValues(users, u => u.age)); // Outputs: { fred: 40, pebbles: 1 }

Output:

{"fred":40,"pebbles":1}

Flowchart:

flowchart: Create an object with the same keys as the provided object and values generated by running the provided function for each value

Live Demo:

See the Pen javascript-basic-exercise-84-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to create a new string with the results of calling a provided function on every character in the calling string.
Next: Write a JavaScript program to replace all but the last number of characters with the specified mask character.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-84.php