Search code examples
jsontypescriptnested

How to get the value from a Nested JSON object from a JSON file using Typescript?


I am new to Typescript. I am trying to iterate a nested JSON file that has segments and products. From the product's value trying to store it and display it on the console.

JSON File :

{
    "int": {
        "name": "internal",
        "products": {
            "test": "Internal Test from Actions"
        }
    },
    "tst": {
        "name": "test",
        "products": {
            "action": "Test Actions"
        }
    }
}

From the above example I am trying to parse the JSON with value "Test Actions" and get the key action and store it as a string.

Basically the typescript needs to iterate through the products and find the value if it is found then get the key and store it in a string.


Solution

  • You could do something like this to get the key and value.

    const printKeyAndValue = (objVal: any) => {
      for (const key of Object.keys(objVal)){
          console.log(key);
          console.log(objVal[key]);   
      }
    };
    
    const obj = {
      'item1': 123,
      'item2': 'some string value'
    };
    
    printKeyAndValue(obj);
    

    Please note the sample I have provided is an object with primitive types only and only top level properties. If you have a nested structure, you must handle accordingly.