我正在寻找一种有效的方法来替换对象内的值(如果它们与特定模式匹配)。
var shapes = {
square: {
attr: {
stroke: '###',
'stroke-width': '%%%'
}
},
circle: {
attr: {
fill: '###',
'stroke-width': '%%%'
}
}
}
例如,我希望能够将所有“###”图案替换为特定形状的颜色:
var square = replace(shapes.square, {
'###': '#333',
'%%%': 23
});
var circle = replace(shapes.circle, {
'###': '#111',
'%%%': 5
});
这将使我能够快速设置各种对象的描边和/或填充值。
有没有办法干净地做到这一点?也许使用 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)