繁体   English   中英

不手动循环遍历 JavaScript 中 JSON 中的每个数组

[英]Not manually loop through every array in JSON in JavaScript

我有一个 JSON,如下所示。 我需要找到name的值,所以在这种情况下它将是“Mark”。 我不知道 object 在 JSON 结构中的深度或在 JSON 中有多少。 不同级别可能有多个。 我知道我可以遍历每个值 object 来查找它。 有没有更简单的方法?

{
  "person": {
    "value": [
      {
        "type": "RANGE",
        "value": {
          "to": "2019-11-05T05:59:59.999Z",
          "from": "1900-01-01T06:00:00.000Z"
        },
        "field": "published",
        "include": true
      },
      {
        "type": "AND",
        "value": [
          {
            "type": "OR",
            "value": [
              {
                "type": "AND",
                "value": [
                  {
                    "type": "OR",
                    "include": true,
                    "value": [
                      {
                        "type": "MATCH",
                        "value": "Mark",
                        "field": "name",
                        "include": true
                      }
                    ]
                  }
                ]
              }
            ]
          },
          {
            "type": "MATCH",
            "value": "37",
            "field": "age",
            "include": true
          }
        ],
        "include": true
      }
    ]
  }
}

这是查找“Mark”的简单递归方式:

function runThroughObject(object) {
  for (const key in object) {
    const value = object[key]

    if (typeof value === 'object' && value !== null) {
      runThroughObject(value)
    }
    else if (value === 'name') {
      console.log(object.value)
    }
  }
}

这是整个工作片段:

 const data = { "person": { "value": [ { "type": "RANGE", "value": { "to": "2019-11-05T05:59:59.999Z", "from": "1900-01-01T06:00:00.000Z" }, "field": "published", "include": true }, { "type": "AND", "value": [ { "type": "OR", "value": [{ "type": "AND", "value": [{ "type": "OR", "include": true, "value": [{ "type": "MATCH", "value": "Mark", "field": "name", "include": true }] }] }] }, { "type": "MATCH", "value": "37", "field": "age", "include": true } ], "include": true } ] } } function runThroughObject(object) { for (const key in object) { const value = object[key] if (typeof value === 'object' && value.== null) { runThroughObject(value) } else if (value === 'name') { console.log(object.value) } } } runThroughObject(data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM