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 and 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 
const mapValues = (obj, fn) =>
  Object.keys(obj).reduce((acc, k) => {
    acc[k] = fn(obj[k], k, obj);
    return acc;
  }, {});
const users = {
  fred: { user: 'fred', age: 40 },
  pebbles: { user: 'pebbles', age: 1 }
};
console.log(mapValues(users, u => u.age));

Sample 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.



JavaScript: Tips of the Day

Returns an array of n-tuples of consecutive elements

Example:

const tips_arr = (n, arr) =>  n > arr.length ? [] : arr.slice(n - 1).map((v, i) =>[...arr.slice(i, i + n - 1), v]);
console.log(tips_arr(2, [1, 2, 3, 4, 5])); 
console.log(tips_arr(3, [1, 2, 3, 4, 5]));
console.log(tips_arr(5, [1, 2, 3, 4]));

Output:

[[1, 2], [2, 3], [3, 4], [4, 5]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
[]