processNested.js 675 B

12345678910111213141516171819202122232425262728
  1. module.exports = function(data){
  2. if (!data || data.length < 1) return {};
  3. let d = {},
  4. keys = Object.keys(data);
  5. for (let i = 0; i < keys.length; i++) {
  6. let key = keys[i],
  7. value = data[key],
  8. current = d,
  9. keyParts = key
  10. .replace(new RegExp(/\[/g), '.')
  11. .replace(new RegExp(/\]/g), '')
  12. .split('.');
  13. for (let index = 0; index < keyParts.length; index++){
  14. let k = keyParts[index];
  15. if (index >= keyParts.length - 1){
  16. current[k] = value;
  17. } else {
  18. if (!current[k]) current[k] = !isNaN(keyParts[index + 1]) ? [] : {};
  19. current = current[k];
  20. }
  21. }
  22. }
  23. return d;
  24. };