I'm looking for an efficient way to replace the values within an object if they match a certain pattern.
var shapes = {
square: {
attr: {
stroke: '###',
'stroke-width': '%%%'
}
},
circle: {
attr: {
fill: '###',
'stroke-width': '%%%'
}
}
}
For instance, i'd like to be able to replace all '###' patterns with a colour for a specific shape:
var square = replace(shapes.square, {
'###': '#333',
'%%%': 23
});
var circle = replace(shapes.circle, {
'###': '#111',
'%%%': 5
});
Which would allow me quickly to set the stroke and/or fill values of various objects.
Is there a way to do this cleanly? Perhaps using Lodash or regex?
Plain JS, no library needed:
var shapes = {
square: {
attr: {
stroke: '###',
'stroke-width': '%%%'
}
},
circle: {
attr: {
fill: '###',
'stroke-width': '%%%'
}
}
}
shapes = JSON.parse(
JSON.stringify(shapes).replace(/###/g,"red").replace(/%%%/g,"23")
)
console.log(shapes);
In lodash, you have a utility function mapValues
function replaceStringsInObject(obj, findStr, replaceStr) {
return _.mapValues(obj, function(value){
if(_.isString(value)){
return value.replace(RegEx(findStr, 'gi'), replaceStr);
} else if(_.isObject(value)){
return replaceStringInObject(value, findStr, replaceStr);
} else {
return value;
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With