mapObject.js.flow 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. * @providesModule mapObject
  8. */
  9. 'use strict';
  10. var hasOwnProperty = Object.prototype.hasOwnProperty;
  11. /**
  12. * Executes the provided `callback` once for each enumerable own property in the
  13. * object and constructs a new object from the results. The `callback` is
  14. * invoked with three arguments:
  15. *
  16. * - the property value
  17. * - the property name
  18. * - the object being traversed
  19. *
  20. * Properties that are added after the call to `mapObject` will not be visited
  21. * by `callback`. If the values of existing properties are changed, the value
  22. * passed to `callback` will be the value at the time `mapObject` visits them.
  23. * Properties that are deleted before being visited are not visited.
  24. *
  25. * @grep function objectMap()
  26. * @grep function objMap()
  27. *
  28. * @param {?object} object
  29. * @param {function} callback
  30. * @param {*} context
  31. * @return {?object}
  32. */
  33. function mapObject(object, callback, context) {
  34. if (!object) {
  35. return null;
  36. }
  37. var result = {};
  38. for (var name in object) {
  39. if (hasOwnProperty.call(object, name)) {
  40. result[name] = callback.call(context, object[name], name, object);
  41. }
  42. }
  43. return result;
  44. }
  45. module.exports = mapObject;