【问题标题】:Substitute multiple object values from a key value table in JavaScript / jQuery从 JavaScript / jQuery 中的键值表替换多个对象值
【发布时间】:2019-08-01 09:11:51
【问题描述】:

我试图弄清楚如何使用键值表替换多个对象值。

我一直在尝试从对常规字符串执行此操作的函数中学习,并使其适用于对象(特别是对象值)。我想也许有办法将这种 (https://stackoverflow.com/a/15604206/2458671) 函数与下面的 replaceValue 函数合并。

var settings = {
  pushItems: {
    "[make_up_policy_attributes][staff_allowed]": true,
    "[make_up_policy_attributes][default_issued_plan_product_id]": "{RPPA}",
    "[make_up_policy_attributes][issued_plan_product_expires]": true,
    "[make_up_policy_attributes][issued_plan_product_duration_months]": 0,
    "[make_up_policy_attributes][issued_plan_product_duration_weeks]": 0,
    "[make_up_policy_attributes][issued_plan_product_duration_days]": 30
  }
}

replaceValue(settings.pushItems, "{RPPA}", 12345 );

function replaceValue(obj, findvalue, replacewith) {
  for (var key in obj) {
    var value = obj[key];
    if (value === findvalue) {
      obj[key] = value.replace(findvalue, replacewith);
    }
  }
}

基本上我想使用一个对象 { searchForValue1: replaceWithValue1, searchForValue2: replaceWithValue2 } 所以如果在 settings.pushItems 对象中找到多个东西,我可以替换它们。

【问题讨论】:

    标签: javascript object string-substitution


    【解决方案1】:

    您可以通过更改 if 语句来做到这一点,如下面的代码:

    var settings = {
      pushItems: {
        "[make_up_policy_attributes][staff_allowed]": true,
        "[make_up_policy_attributes][default_issued_plan_product_id]": "{RPPA}",
        "[make_up_policy_attributes][issued_plan_product_expires]": true,
        "[make_up_policy_attributes][issued_plan_product_duration_months]": 0,
        "[make_up_policy_attributes][issued_plan_product_duration_weeks]": 0,
        "[make_up_policy_attributes][issued_plan_product_duration_days]": 30,
        "exampleValue1": "abc1",
        "exampleValue2": "abc2",
        "exampleValue3": "abc3",
      }
    }
    
    var replaceObject = {
      "{RPPA}": 12345,
      "abc2": "newValue2",
      true: false
    }
    
    replaceValue(settings.pushItems, replaceObject);
    
    function replaceValue(obj, replaceObject) {
      for (var key in obj) {
        var value = obj[key];
        if (replaceObject.hasOwnProperty(value)) obj[key] = replaceObject[value];
      }
    }
    
    console.log(settings.pushItems);

    希望这会有所帮助!

    编辑:更新 if 条件。

    【讨论】:

    • 非常感谢您。为什么反转布尔值不起作用?例如,如果我想将 settings.pushItems 中的 true 值更改为 false,这似乎不起作用。我试过{true: false}{true: !true} 无济于事。
    • @Matthew 我已经更新了代码 sn-p 中的 if 条件。请检查。
    猜你喜欢
    • 2015-03-31
    • 1970-01-01
    • 2021-05-01
    • 2018-01-09
    • 2020-05-23
    • 2021-12-11
    • 1970-01-01
    • 2017-02-18
    • 2012-07-09
    相关资源
    最近更新 更多