object_utils.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. var stringUtils = require('utils/string_utils');
  19. module.exports = {
  20. isChild: function(obj)
  21. {
  22. for (var k in obj) {
  23. if (obj.hasOwnProperty(k)) {
  24. if (obj[k] instanceof Object) {
  25. return false;
  26. }
  27. }
  28. }
  29. return true;
  30. },
  31. recursiveKeysCount: function(obj) {
  32. if (!(obj instanceof Object)) {
  33. return null;
  34. }
  35. var self = this;
  36. function r(obj) {
  37. var count = 0;
  38. for (var k in obj) {
  39. if(self.isChild(obj[k])){
  40. count++;
  41. } else {
  42. count += r(obj[k]);
  43. }
  44. }
  45. return count;
  46. }
  47. return r(obj);
  48. },
  49. recursiveTree: function(obj) {
  50. if (!(obj instanceof Object)) {
  51. return null;
  52. }
  53. var self = this;
  54. function r(obj,parent) {
  55. var leaf = '';
  56. for (var k in obj) {
  57. if(self.isChild(obj[k])){
  58. leaf += k + ' ('+parent+')' + '<br/>';
  59. } else {
  60. leaf += r(obj[k],parent +'/' + k);
  61. }
  62. }
  63. return leaf;
  64. }
  65. return r(obj,'');
  66. },
  67. /**
  68. * Gets value of property path.
  69. *
  70. * @param propertyPath
  71. * Format is 'a.b.c'
  72. * @return Returns <code>undefined</code> when path does not exist.
  73. */
  74. getProperty: function (object, propertyPath) {
  75. var props = propertyPath.split('.');
  76. for ( var c = 0; c < props.length - 1 && object; c++) {
  77. object = object[props[c]];
  78. if (object === null) {
  79. break;
  80. }
  81. }
  82. if (object != null) {
  83. return object[props[props.length - 1]];
  84. }
  85. return undefined;
  86. }
  87. };