javascript - 用javascript中的对象值替换字符串值
问题描述
let formula = {width} + {height} + {weight} + {custom}
var custom = []
custom[25] = 2
custom[125] = 4
custom[225] = 5
{
'width': 25,
'height': 45,
'weight': 95,
'custom': {0: 100, 1: 200, 2: 300}
}
我有上述类型的对象,我想用我上面的对象值替换公式变量。我想用对象值替换我的公式值。另外,我的对象有一个 kyw,其名称类似于“custom”,该键在某些可用的对象中不是必需的,而有些则不是。现在我想用 {custom} 键替换自定义对象。
我想要这样
1) 25 + 45 + 95 + 100
2) 25 + 45 + 95 + 200
4) 25 + 45 + 95 + 300
我试过这个
custom.forEach((value, i) => {
let output = formula.replace(/{(\w+?)}/g, (m, c) => myobject[c]);
});
可能的类型公式
let formula1 = {width} + {height} + {weight} - {custom}
let formula2 = {width} * {height} - {weight}
let formula3 = {width} * {height} - {weight} * {custom}
解决方案
您用于模板文字的语法不正确,在这样的问题中也不需要正则表达式。
这个片段可以满足您的需求。
let obj = {
'width': 25,
'height': 45,
'weight': 95,
'custom': {
0: 100,
1: 200,
2: 300
}
}
let operatorList = prompt("Enter the 3 operators you would like to use. eg '++-'").split("").slice(0, 3) // The string used to join the items values from the object
// Iterate over each key of 'obj.custom'
for (let key in obj.custom) {
let valuesArray = []
// Iterate through each value of 'obj'
for (let value of Object.values(obj)) {
// Make sure that the value is a number or a string
if (typeof value === "object") continue;
// Append the value to the 'valuesArray'
valuesArray.push(value)
}
valuesArray.push(obj.custom[key]) // Add the correct value from the `obj.custom` object
let valuesAndOperators = []
let listClone = Array.from(operatorList) // Create a clone of the list of operators
for (let value of valuesArray) {
valuesAndOperators.push(value) // Add values to new array
valuesAndOperators.push(listClone.shift()) // Add operators between values
}
console.log(`${parseInt(key) + 1}) ${valuesAndOperators.join(" ")}`)
}
推荐阅读
- azure - Datafactory V2 将“\N”空值替换为空白
- php - 在 PHP 中使用 OpenWeatherMap 预报 API
- python - 需要帮助改进文本处理程序(Python 3)
- cordova - “窗口”类型上不存在属性“科尔多瓦”。: 离子
- python - Seaborn 箱线图水平线标注
- sql - JPA 通过 ForeginKey 选择项目
- java - GET 不显示在 java 动态 Web 项目中实现的 Posted 对象
- mysql - Mysql查询-带有子查询结果的where子句
- php - 如何在 Laravel 中制作多语言(本地化)?
- mysql - 无法从 Docker 容器连接到主机 MySQL 数据库