Home > Net >  Replacing a key value pair with a new key value pair inside a nested object
Replacing a key value pair with a new key value pair inside a nested object

Time:10-26

I am having trouble effectively identifying/replacing the value I need inside an Object for an editing pay rates application.


    {
        Physicians: {
          telehealth: {
            orgName: "ORG B",
            weekdayEncounters: { type: "each", value: 15 },
            weeknightEncounters: { type: "each", value: 16.25 },
            weekendDayEncounters: { type: "each", value: 16.25 },
            weekendNightEncounters: { type: "each", value: 17.25 },
            holidayEncounters: { type: "each", value: 17.25 },
            stipend: { type: "lump", value: 0 },
          },
        },
        NonPhysicians: {
          telehealth: {
            orgName: "ORG B",
            weekdayEncounters: { type: "each", value: 15 },
            weeknightEncounters: { type: "each", value: 16.25 },
            weekendDayEncounters: { type: "each", value: 16.25 },
            weekendNightEncounters: { type: "each", value: 17.25 },
            holidayEncounters: { type: "each", value: 17.25 },
            stipend: { type: "lump", value: 0 },
          },
        },
        date: "07-2021",
        orgName: "ORG B",
        ltc: false,
      }

I am looking to replace the value inside the deepest object depending on the field that is edited. At this point I just keep getting messier and messier code trying to dig into the object read it and then replace the correct value. I have an example in written up here. Please take it easy on me I am still learning. Advice would be greatly appreciated.My issue currenlty is that I am returning an array full of undefineds and then the one object I need. Thanks in advance.

CodePudding user response:

I went into your example and took the top level object 'NEWRATES'. The example code below goes through each of the sub-object NEWRATES['ltc'][0]['Infinity']['Physicians']['associates'], and prints the value under the key 'value'. It also does a quick check for the type since the lowest level contains some keys that map to strings, e.g. (orgName: "Infinity").

The Object.entries function call is necessary to make the indicated object NEWRATES[...] iterable.

for( let [key,value] of Object.entries(NEWRATES["ltc"][0]['Infinity']['Physicians']['associates']) ){
    if(typeof value == "object"){
        console.log('value is: '   value.value);
    }
}

This should be enough to get you going again. Simply replace the top level keys from 'ltc' -> 'standard' , 'Physicians' -> 'NonPhysicians' to iterate through the other portions of the top level object.

  • Related