首页 > 解决方案 > 用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}

标签: javascriptregex

解决方案


您用于模板文字的语法不正确,在这样的问题中也不需要正则表达式。

这个片段可以满足您的需求。

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(" ")}`)
}


推荐阅读