Last active
August 29, 2015 14:02
-
-
Save bodokaiser/5f958f6b968367f6a0e5 to your computer and use it in GitHub Desktop.
Ultimate string parsing map reduce action.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var string = 'colors:red, colors:blue, sizes:42, sizes:44'; | |
var obj = string.split(', ') | |
.map(function(entry) { | |
return entry.split(':').reduce(function(prev, curr) { | |
if (!prev.name) { | |
prev.name = curr; | |
prev.value = ''; | |
} else { | |
prev.value += curr; | |
} | |
return prev; | |
}, {}); | |
}) | |
.reduce(function(prev, curr) { | |
if (!prev.hasOwnProperty(curr.name)) { | |
prev[curr.name] = [curr.value]; | |
} | |
if (!~prev[curr.name].indexOf(curr.value)) { | |
prev[curr.name].push(curr.value); | |
} | |
return prev; | |
}, {}); | |
// { colors: ['red', 'blue'], sizes: [42, 44] } | |
console.log(obj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment