Guest User

Untitled

a guest
Jan 19th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. var structure = {
  2. name: 'alpha',
  3. array: [
  4. { name: 'beta' },
  5. { name: 'gamma' }
  6. ],
  7. object: {
  8. name: 'delta',
  9. array: [
  10. { name: 'epsilon' }
  11. ]
  12. }
  13. };
  14.  
  15. // expected result: [ 'alpha', 'beta', 'gamma', 'delta', 'epsilon' ]
  16.  
  17. function getPropertyRecursive(obj, property) {
  18. var values = [];
  19. _.each(obj, function(value, key) {
  20. if (key === property) {
  21. values.push(value);
  22. } else if (_.isObject(value)) {
  23. values = values.concat(getPropertyRecursive(value, property));
  24. }
  25. });
  26. return values;
  27. }
  28.  
  29. _.mixin({
  30. toPairsDeep: obj => _.flatMap(
  31. _.toPairs(obj), ([k, v]) =>
  32. _.isObjectLike(v) ? _.toPairsDeep(v) : [[k, v]])
  33. });
  34.  
  35. result = _(structure)
  36. .toPairsDeep()
  37. .map(1)
  38. .value()
  39.  
  40. result = _(structure)
  41. .toPairsDeep()
  42. .filter(([k, v]) => k === 'name')
  43. .map(1)
  44. .value()
  45.  
  46. function walk(o, f) {
  47. f(o);
  48. if(typeof o !== 'object') return;
  49. if(Array.isArray(o)) return o.forEach(e => walk(e, f));
  50. for(let prop in o) walk(o[prop], f);
  51. }
  52.  
  53. const arr = [];
  54. walk(structure, x => if(x !== undefined && x.name) arr.push(x.name));
  55.  
  56. function walk(o, f, context) {
  57. f(o, context);
  58. if(typeof o !== 'object') return context;
  59. if(Array.isArray(o)) return o.forEach(e => walk(e, f, context)), context;
  60. for(let prop in o) walk(o[prop], f, context);
  61. return context;
  62. }
  63.  
  64. const arr = walk(structure, (x, context) => {
  65. if(x !== undefined && x.name) context.push(x.name);
  66. }, []);
  67.  
  68. _.mixin({
  69. extractLeaves: (obj, filter, subnode) => {
  70. var filterKv = _(filter).toPairs().flatMap().value()
  71. var arr = _.isArray(obj) ? obj : [obj]
  72. return _.flatMap(arr, (v, k) => {
  73. if (v[filterKv[0]] === filterKv[1]) {
  74. var vClone = _.clone(v)
  75. delete vClone[subnode]
  76. return vClone
  77. } else {
  78. return _.extractLeaves(v[subnode], filter, subnode)
  79. }
  80. })
  81. }
  82. });
  83.  
  84. {
  85. "name": "raka",
  86. "type": "dir",
  87. "children": [{
  88. "name": "riki",
  89. "type": "dir",
  90. "children": [{
  91. "name": "roko",
  92. "type": "file"
  93. }]
  94. }]
  95. }
  96.  
  97. _.extractLeaves(result, {type: "file"}, "children")
  98.  
  99. [
  100. {
  101. "name": "roko",
  102. "type": "file"
  103. }
  104. ]
Add Comment
Please, Sign In to add comment