JS:替换对象中与模式匹配的所有字符串值? [英] JS: Replacing all string values in an object that match a pattern?
本文介绍了JS:替换对象中与模式匹配的所有字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种有效的方法来替换对象中与特定模式匹配的值.
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.
有没有办法做到这一点?也许使用Lodash或正则表达式?
Is there a way to do this cleanly? Perhaps using Lodash or regex?
推荐答案
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;
}
});
}
这篇关于JS:替换对象中与模式匹配的所有字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文