Convert dot notation with subs [n] to object-array-like


SUBMITTED BY: antfuentes87

DATE: Nov. 25, 2015, 12:50 a.m.

FORMAT: Text only

SIZE: 700 Bytes

HITS: 745

  1. var test = {};
  2. for (var key in eventData) {
  3. key.split('.').reduce(function (lastReturn, prop, index, arr) {
  4. if (!lastReturn[prop]) {
  5. if (arr.length - 1 === index) {
  6. lastReturn[prop] = eventData[key];
  7. } else {
  8. lastReturn[prop] = {};
  9. }
  10. }
  11. return lastReturn[prop];
  12. }, test);
  13. }
  14. for (var key in test) {
  15. if (key.match(/\[\d+\]/)) {
  16. var prefix = key.replace(/\[\d+\]/, '');
  17. test[prefix] = test[prefix] || [];
  18. if (typeof test[key] === 'object') {
  19. test[key]
  20. }
  21. test[prefix].push(test[key]);
  22. delete test[key];
  23. }
  24. }

comments powered by Disqus