mapObject.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. */
  8. 'use strict';
  9. var hasOwnProperty = Object.prototype.hasOwnProperty;
  10. /**
  11. * Executes the provided `callback` once for each enumerable own property in the
  12. * object and constructs a new object from the results. The `callback` is
  13. * invoked with three arguments:
  14. *
  15. * - the property value
  16. * - the property name
  17. * - the object being traversed
  18. *
  19. * Properties that are added after the call to `mapObject` will not be visited
  20. * by `callback`. If the values of existing properties are changed, the value
  21. * passed to `callback` will be the value at the time `mapObject` visits them.
  22. * Properties that are deleted before being visited are not visited.
  23. *
  24. * @grep function objectMap()
  25. * @grep function objMap()
  26. *
  27. * @param {?object} object
  28. * @param {function} callback
  29. * @param {*} context
  30. * @return {?object}
  31. */
  32. function mapObject(object, callback, context) {
  33. if (!object) {
  34. return null;
  35. }
  36. var result = {};
  37. for (var name in object) {
  38. if (hasOwnProperty.call(object, name)) {
  39. result[name] = callback.call(context, object[name], name, object);
  40. }
  41. }
  42. return result;
  43. }
  44. module.exports = mapObject;