objectProperties.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. function isObject(value) {
  2. if (value === null) return false;
  3. if (typeof value !== 'object') return false;
  4. if (Array.isArray(value)) return false;
  5. if (Object.prototype.toString.call(value) === '[object Date]') return false;
  6. return true;
  7. }
  8. export function clone(object) {
  9. return Object.keys(object).reduce((values, name) => {
  10. if (object.hasOwnProperty(name)) {
  11. values[name] = object[name];
  12. }
  13. return values;
  14. }, {});
  15. }
  16. /*
  17. * Flatten nested object into a single level object with 'foo.bar' property names
  18. *
  19. * The parameter object is left unchanged. All values in the returned object are scalar.
  20. *
  21. * cloneAndFlatten({ a: 1, b: { c: 2 }, d: { e: 3, f: { g: 4, h: 5 } }, i: { j: 6 } }, ['i'])
  22. * // { a: 1, 'b.c': 2, 'd.e': 3, 'd.f.g': 4, 'd.f.h': 5, i: { j: 6 } } }
  23. *
  24. * @param {Object} object
  25. * @param {String[]} excludedProperties
  26. * @return {Object}
  27. */
  28. export function cloneAndFlatten(object, excludedProperties = []) {
  29. if (typeof object !== 'object') {
  30. throw new Error('Expecting an object parameter');
  31. }
  32. return Object.keys(object).reduce((values, name) => {
  33. if (!object.hasOwnProperty(name)) return values;
  34. if (isObject(object[name])) {
  35. if (excludedProperties.indexOf(name) === -1) {
  36. let flatObject = cloneAndFlatten(object[name]);
  37. Object.keys(flatObject).forEach(flatObjectKey => {
  38. if (!flatObject.hasOwnProperty(flatObjectKey)) return;
  39. values[name + '.' + flatObjectKey] = flatObject[flatObjectKey];
  40. })
  41. } else {
  42. values[name] = clone(object[name]);
  43. }
  44. } else {
  45. values[name] = object[name];
  46. }
  47. return values;
  48. }, {});
  49. };
  50. /*
  51. * Clone flattened object into a nested object
  52. *
  53. * The parameter object is left unchanged.
  54. *
  55. * cloneAndNest({ a: 1, 'b.c': 2, 'd.e': 3, 'd.f.g': 4, 'd.f.h': 5 } )
  56. * // { a: 1, b: { c: 2 }, d: { e: 3, f: { g: 4, h: 5 } } }
  57. *
  58. * @param {Object} object
  59. * @return {Object}
  60. */
  61. export function cloneAndNest(object) {
  62. if (typeof object !== 'object') {
  63. throw new Error('Expecting an object parameter');
  64. }
  65. return Object.keys(object).reduce((values, name) => {
  66. if (!object.hasOwnProperty(name)) return values;
  67. name.split('.').reduce((previous, current, index, list) => {
  68. if (previous != null) {
  69. if (typeof previous[current] === 'undefined') previous[current] = {};
  70. if (index < (list.length - 1)) {
  71. return previous[current];
  72. };
  73. previous[current] = object[name];
  74. }
  75. }, values)
  76. return values;
  77. }, {})
  78. }