processNested.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const OBJECT_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Object.prototype);
  2. const ARRAY_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Array.prototype);
  3. module.exports = function(data){
  4. if (!data || data.length < 1) return {};
  5. let d = {},
  6. keys = Object.keys(data);
  7. for (let i = 0; i < keys.length; i++) {
  8. let key = keys[i],
  9. value = data[key],
  10. current = d,
  11. keyParts = key
  12. .replace(new RegExp(/\[/g), '.')
  13. .replace(new RegExp(/\]/g), '')
  14. .split('.');
  15. for (let index = 0; index < keyParts.length; index++){
  16. let k = keyParts[index];
  17. // Ensure we don't allow prototype pollution
  18. const IN_ARRAY_PROTOTYPE = ARRAY_PROTOTYPE_KEYS.includes(k) && Array.isArray(current);
  19. if (OBJECT_PROTOTYPE_KEYS.includes(k) || IN_ARRAY_PROTOTYPE) {
  20. continue;
  21. }
  22. if (index >= keyParts.length - 1){
  23. current[k] = value;
  24. } else {
  25. if (!current[k]) current[k] = !isNaN(keyParts[index + 1]) ? [] : {};
  26. current = current[k];
  27. }
  28. }
  29. }
  30. return d;
  31. };