I have an API returning the following string
styles: "background #2b2b2b; color: #FFFFFF"
I need to convert this on the fly into an object like so
styles: { background: '#2b2b2b', color: '#FFFFFF' }
How best to achieve this
I have an API returning the following string
styles: "background #2b2b2b; color: #FFFFFF"
I need to convert this on the fly into an object like so
styles: { background: '#2b2b2b', color: '#FFFFFF' }
How best to achieve this
Please do some searching before asking. People are going to rate your question down now. But here's an answer anyway...
const str = "background #2b2b2b; color: #FFFFFF"
const obj = str.split('; ').reduce((acc, keyVal) => {
const [key, val] = keyVal.split(' ')
acc[key] = val
return acc
}, {})
console.log(obj) // {background: "#2b2b2b", color:: "#FFFFFF"}
// if str was just 'background #2b2b2b;' it would include the ;
// {background: "#2b2b2b;"}
As someone mentioned your string is inconsistent so you'll need to fix the string format or add ways to handle edge cases.
Update: Perhaps a more flexible way would be to use RegExp. I'm not the best at writing RegExps so it could probably be improved.
// add acceptable characters in the brackets [ ]
const re = /([a-z-]+):\s?([()'"#a-z0-9]+);/gi
const str = 'background: #2b2b2b; color: #FFFFFF;background-url: url("test");'
const styles = {}
let next
while ((next = re.exec(str)) !== null) {
const key = next[1]
const value = next[2]
// or const [ _, key, value ] = next
styles[key] = value
}
console.log(styles)
/*
{
background: '#2b2b2b',
color: '#FFFFFF',
'background-url': 'url("test")'
}
*/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
Regular expression alternative https://regex101.com/r/ZmAW1m
var o = {}, s = "background #2b2b2b; color: #FFFFFF"
s.replace(/([^: ]+)[: ]+([^; ]+)[; ]*/g, (m, k, v) => o[k] = v)
console.log(o)
You can convert
let styles = "background #2b2b2b; color: #FFFFFF";
into
stylesObj = {background: styles.split(";")[0].trim().split(" ")[1],
color: styles.split(";")[1].trim().split(" ")[1]}
// {background: "#2b2b2b", color: "#FFFFFF"}
and you should get it in the form that you want.
EDIT
Added the .trim()
, otherwise it does not work if the string has extra spaces.