pluck.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. 'use strict';
  2. var _require = require('../helpers/is'),
  3. isArray = _require.isArray,
  4. isObject = _require.isObject;
  5. var nestedValue = require('../helpers/nestedValue');
  6. var buildKeyPathMap = function buildKeyPathMap(items) {
  7. var keyPaths = {};
  8. items.forEach(function (item, index) {
  9. function buildKeyPath(val, keyPath) {
  10. if (isObject(val)) {
  11. Object.keys(val).forEach(function (prop) {
  12. buildKeyPath(val[prop], "".concat(keyPath, ".").concat(prop));
  13. });
  14. } else if (isArray(val)) {
  15. val.forEach(function (v, i) {
  16. buildKeyPath(v, "".concat(keyPath, ".").concat(i));
  17. });
  18. }
  19. keyPaths[keyPath] = val;
  20. }
  21. buildKeyPath(item, index);
  22. });
  23. return keyPaths;
  24. };
  25. module.exports = function pluck(value, key) {
  26. if (value.indexOf('*') !== -1) {
  27. var keyPathMap = buildKeyPathMap(this.items);
  28. var keyMatches = [];
  29. if (key !== undefined) {
  30. var keyRegex = new RegExp("0.".concat(key), 'g');
  31. var keyNumberOfLevels = "0.".concat(key).split('.').length;
  32. Object.keys(keyPathMap).forEach(function (k) {
  33. var matchingKey = k.match(keyRegex);
  34. if (matchingKey) {
  35. var match = matchingKey[0];
  36. if (match.split('.').length === keyNumberOfLevels) {
  37. keyMatches.push(keyPathMap[match]);
  38. }
  39. }
  40. });
  41. }
  42. var valueMatches = [];
  43. var valueRegex = new RegExp("0.".concat(value), 'g');
  44. var valueNumberOfLevels = "0.".concat(value).split('.').length;
  45. Object.keys(keyPathMap).forEach(function (k) {
  46. var matchingValue = k.match(valueRegex);
  47. if (matchingValue) {
  48. var match = matchingValue[0];
  49. if (match.split('.').length === valueNumberOfLevels) {
  50. valueMatches.push(keyPathMap[match]);
  51. }
  52. }
  53. });
  54. if (key !== undefined) {
  55. var collection = {};
  56. this.items.forEach(function (item, index) {
  57. collection[keyMatches[index] || ''] = valueMatches;
  58. });
  59. return new this.constructor(collection);
  60. }
  61. return new this.constructor([valueMatches]);
  62. }
  63. if (key !== undefined) {
  64. var _collection = {};
  65. this.items.forEach(function (item) {
  66. if (nestedValue(item, value) !== undefined) {
  67. _collection[item[key] || ''] = nestedValue(item, value);
  68. } else {
  69. _collection[item[key] || ''] = null;
  70. }
  71. });
  72. return new this.constructor(_collection);
  73. }
  74. return this.map(function (item) {
  75. if (nestedValue(item, value) !== undefined) {
  76. return nestedValue(item, value);
  77. }
  78. return null;
  79. });
  80. };