You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.6 KiB

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