skip to Main Content

Below is my nested object.

editedFields {
  "TAX_INFORMATION": {
     "TAX VALUE INFORMATION": {
        "Improvement Value": "$812,57"
    }
  }
}
const handleValues = (section: string, key: string, value: string | undefined) {
    console.log(section) - TAX_INFORMATION
    console.log(key) - Improvement Value
    console.log(editedFields[section]?.[key]) - undefined
}

I need the output should be the value "$812,57".

Need some valuable help.

2

Answers


  1. You can modify the handlevalue as such

    const handleValues = (section: string, key: string, value: string | undefined) => {
      console.log(section);
      console.log(key);
      const nestedSection = editedFields[section]["TAX VALUE INFORMATION"];
      console.log(nestedSection[key]);
    }
    

    and then call it like this to get $812,57

    handleValues("TAX_INFORMATION", "Improvement Value", undefined);
    
    Login or Signup to reply.
  2.     editedFields[section] = 
    {
    "TAX VALUE INFORMATION": {
                "Improvement Value": "$812,57"
            }
    }
    

    editedFields[section]?.[Improvement Value] – does not exists in you data.
    editedFields[section]?.["TAX VALUE INFORMATION]["Improvement Value"] will give you the data.

    If you do not know the mid level key and need to find a specific key in nested object you will need ot right some extra code to get that.
    here is a sample of such code.

    const dig = (obj, target) =>
      target in obj
        ? obj[target]
        : Object.values(obj).reduce((acc, val) => {
            if (acc !== undefined) return acc;
            if (typeof val === 'object') return dig(val, target);
          }, undefined);
    
    const data = {
      foo: {
        foz: [1, 2, 3],
        bar: { baz: ['a', 'b', 'c'] },
      },
    };
    
    dig(data, 'foz'); // [1, 2, 3]
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search