javascript 动态生成的键遍历嵌套对象

m2xkgtsf  于 2023-03-16  发布在  Java
关注(0)|答案(4)|浏览(120)

我试图遍历JSON对象以从中获取键的值,并且能够做到这一点。

这是我试过的代码

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

有没有其他方法来遍历这个动态json,因为多个 forEach 似乎不合适,或者我可以直接获得**“PRODUCT”**键值而不需要遍历?
谢谢你帮忙。

vxf3dgd4

vxf3dgd41#

Javascript已经有一个内置的json步行者:JSON.strinfigy

let products = []

JSON.stringify(json, (k, v) => {
    if (k === 'productName')
        products.push(v)
    return v
})
esbemjvw

esbemjvw2#

只需创建如下所示递归函数即可解决该问题:

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

gstyhher3#

这里可以使用递归函数。

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

uelo1irk4#

可以使用递归

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

相关问题