skip to Main Content

I am trying to traverse json object to get value of a key from it and was able to do that.

This is the code which i have tried :

var json = {
  "SERVICE": {
    "Support1": {
      "MODULE": {
        "Something": {
          "SUBMODULE": {
            "Abc": {
              "PRODUCT": [{
                "productName": "something1",
              }]
            }
          }
        }
      }
    },
    "Support2": {
      "MODULE": {
        "Something2": {
          "SUBMODULE": {
            "Abc2": {
              "PRODUCT": [{
                "productName": "something10",
              }]
            }
          }
        }
      }
    }
  },
}

Object.keys(json.SERVICE).forEach(service => {
  var module = Object.keys(json.SERVICE[service].MODULE);
  module.forEach(modules => {
    var sub_module = Object.keys(json.SERVICE[service].MODULE[modules].SUBMODULE);
    sub_module.forEach(products => {
      var products = json.SERVICE[service].MODULE[modules].SUBMODULE[products].PRODUCT;
      products.forEach(value => {
        console.log(value.productName)
      })
    })
  })
})

Is there any other way to traverse this dynamic json because multiple forEach doesn’t seems proper or can i get the "PRODUCT" key values directly without traversing ?

Thank you for helping .

4

Answers


  1. A recursive function can be used here instead.

    let o={SERVICE:{Support1:{MODULE:{Something:{SUBMODULE:{Abc:{PRODUCT:[{productName:"something1"}]}}}}},Support2:{MODULE:{Something2:{SUBMODULE:{Abc2:{PRODUCT:[{productName:"something10"}]}}}}}}};
    const getProducts = o => Object.entries(o).flatMap(([k, v]) => k === 'PRODUCT' ? 
      v.map(p => p.productName) : v === Object(v) ? getProducts(v) : []);
    console.log(getProducts(o));
    Login or Signup to reply.
  2. You can use recursion

    const json = {
      "SERVICE": {
        "Support1": {
          "MODULE": {
            "Something": {
              "SUBMODULE": {
                "Abc": {
                  "PRODUCT": [{
                    "productName": "something1",
                  }]
                }
              }
            }
          }
        },
        "Support2": {
          "MODULE": {
            "Something2": {
              "SUBMODULE": {
                "Abc2": {
                  "PRODUCT": [{
                    "productName": "something10",
                  }]
                }
              }
            }
          }
        }
      },
    }
    
    function doRecursion(json, key) {
      for (let objectKey in json) {
        if (objectKey === key) {
          return json[objectKey]
    
        } else if (typeof json[objectKey] === 'object') {
          return doRecursion(json[objectKey], key)
        }
      }
    }
    
    console.log(doRecursion(json, 'PRODUCT'))
    Login or Signup to reply.
  3. Just create recursive function like code below to solve that problem:

    var json = {"SERVICE":{"Support1":{"MODULE":{"Something":{"SUBMODULE":{"Abc":{"PRODUCT":[{"productName":"something1","productCode":"1234","productHierarchy":"yz"},{"productName":"something2","productCode":"124","productHierarchy":"ddd"}]}}}}},"Support2":{"MODULE":{"Something2":{"SUBMODULE":{"Abc2":{"PRODUCT":[{"productName":"something1","productCode":"1234","productHierarchy":"yz"},{"productName":"something2","productCode":"124","productHierarchy":"ddd"}]}}}}}}};
    
    let getData = (value, result = []) => {
      if(value instanceof Object || value instanceof Array) {
        for(v in value) {
          if (typeof value[v] === 'string') {
            result.push(value);
          } else {
            getData(value[v], result);
          }
        }
      }
      return [...new Set(result.map(v => JSON.stringify(v)))].map(v => JSON.parse(v));
    }
    
    console.log(getData(json));
    Login or Signup to reply.
  4. Javascript already has a built-in json walker: JSON.strinfigy:

    let products = []
    
    JSON.stringify(json, (k, v) => {
        if (k === 'productName')
            products.push(v)
        return v
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search