processNested.js 902 B

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