我正在寻找一种有效的方法来替换对象中的值,如果它们匹配某个模式。
var shapes = {
square: {
attr: {
stroke: '###',
'stroke-width': '%%%'
}
},
circle: {
attr: {
fill: '###',
'stroke-width': '%%%'
}
}
}
Run Code Online (Sandbox Code Playgroud)
例如,我希望能够用特定形状的颜色替换所有“###”图案:
var square = replace(shapes.square, {
'###': '#333',
'%%%': 23
});
var circle = replace(shapes.circle, {
'###': '#111',
'%%%': 5
});
Run Code Online (Sandbox Code Playgroud)
这将允许我快速设置各种对象的笔触和/或填充值。
有没有办法干净地做到这一点?也许使用 Lodash 或正则表达式?
纯 JS,不需要库:
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);Run Code Online (Sandbox Code Playgroud)
在 lodash 中,你有一个效用函数 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;
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3445 次 |
| 最近记录: |