0

I'm trying to figure out how to replace multiple object values using a key-value table.

I've been trying to learn from functions that do this on regular strings, and make it work for objects (specifically object values). I thought maybe there could be a way to merge this (https://stackoverflow.com/a/15604206/2458671) kind of function with my replaceValue function below.

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);
    }
  }
}

Basically I want to use an object { searchForValue1: replaceWithValue1, searchForValue2: replaceWithValue2 } so I can substitute multiple things if they are found in the settings.pushItems object.

Matthew
  • 59
  • 6

1 Answers1

0

You can do so by changing your if statement like in the below code:

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);

Hope this helps!

Edit: Updated if condition.

Sohan
  • 66
  • 1
  • 4
  • Thank you so much for this. Why doesn't it work to invert booleans? For example, if I wanted to change those `true` values in **settings.pushItems** to `false` this seems to not work. I tried `{true: false}` and `{true: !true}` to no avail. – Matthew Aug 01 '19 at 18:04
  • @Matthew I have updated the if condition in the code snippet. Please check. – Sohan Aug 02 '19 at 05:07