Created
June 19, 2014 09:36
-
-
Save bodokaiser/04b102abb3c366ffb10a to your computer and use it in GitHub Desktop.
nested string parser
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 = 'name:stock, vars:colors:red, vars:colors:blue,vars:sizes:44, really:nasty:nested'; | |
function parse(array) { | |
return array | |
.map(function(item) { | |
var parts = item.split(':'); | |
return { | |
key: parts.shift(), | |
value: parts.join(':') | |
}; | |
}) | |
.reduce(function(prev, curr) { | |
var pair = prev.find(function(item) { | |
return item.key === curr.key; | |
}); | |
if (!pair) { | |
pair = { | |
key: curr.key, | |
value: [curr.value] | |
}; | |
prev.push(pair); | |
} else { | |
if (!~pair.value.indexOf(curr.value)) { | |
pair.value.push(curr.value); | |
} | |
} | |
return prev; | |
}, []) | |
.reduce(function(prev, curr) { | |
if (Array.isArray(curr.value) && curr.value.join('').contains(':')) { | |
curr.value = parse(curr.value); | |
} | |
if (!prev[curr.key]) { | |
prev[curr.key] = curr.value; | |
} | |
return prev; | |
}, {}); | |
} | |
var obj = parse(string.split(', ')); | |
// { name: ['stock'], vars: { colors: ['red', 'blue'], sizes: ['44'] }, really: { nasty: ['nested'] } }; | |
console.log(obj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment