【问题标题】:Finding a key in json在 json 中查找密钥
【发布时间】:2019-04-18 09:04:48
【问题描述】:

我有以下 json:

let object = {
"statusCode": 200,
"body": [{
        "id": "3",
        "externalId": "billgates",
        "status": "active",
        "createdAt": "2018-11-14T08:36:50.967Z",
        "updatedAt": "2018-11-14T08:36:50.967Z",
        "firstName": "yehu",
        "lastName": "da",
        "email": "bg@g.com"
    }
],
"headers": {
    "x-powered-by": "Express",
    "access-control-allow-origin": "*",
    "content-type": "application/json; charset=utf-8",
    "content-length": "189",
    "etag": "W/\"bd-Emx3/KChQLzf9+6bgFSHXPQgDTM\"",
    "date": "<<Masked>>",
    "connection": "close"
},
"request": {
    "uri": {
        "protocol": "http:",
        "slashes": true,
        "auth": null,
        "host": "mysite",
        "port": "4202",
        "hostname": "mysite",
        "hash": null,
        "search": "?username=billgates",
        "query": "username=billgates",
        "pathname": "/v1/users",
        "path": "/v1/users?username=billgates",
        "href": "http://mysite"
    },
    "method": "GET",
    "headers": {
        "Content-Type": "application/json",
        "accept": "application/json",
        "content-length": 2
    }
}

}

我写了一个函数,它获取一个键和一个值,如果在 json 中找到具有该值的键返回 true,否则返回 false,这是函数:

let key = "externalId";
let value = "bilgates"
let findValue = function findValue(obj, key, value) {
            for(let localKey in obj){
                if(obj.hasOwnProperty(localKey)){
                    if(localKey === key){
                        res = obj[localKey] === value;
                        return res;
                    }
                    else{
                        let val = obj[localKey];
                        findValue(val, key, value);
                    }
                }
            }
        }
 let res = findValue(object, key, value)
 console.log(res);

在 VS Code (node.js) 中运行该函数后,出现以下错误:

RangeError: 超出最大调用堆栈大小

调试功能后,我没有发现问题。似乎在某个时间点之后,localKey 将始终为零,而 obj[localKey] 将始终为 3。

【问题讨论】:

  • hint ... 是"id": "3", 导致了问题(您需要在递归之前检查obj[localKey] 是否是一个实际的对象...您还需要正确递归 - 因为除非密钥位于顶层,一旦修复无限递归,您将始终未定义
  • 请注意,如果您正在处理没有有意义的内部原型的普通对象,则hasOwnProperty 检查是多余的。 (或者只使用Object.keys/entries 代替,它只直接在对象上迭代属性)
  • 最快的 fix 为您的代码pastebin.com/8YQb4mQ3 - 但我根本不会这样做
  • @Bravo 为什么你不会这样做。有什么问题?
  • 老实说,我不知道我为什么这么说:p 我很快尝试了其他方法,并意识到这部分语句的错误:

标签: javascript node.js json recursion


【解决方案1】:

虽然有不同的解决方案,但您仍然可以尝试以下方法

let object = {
"statusCode": 200,
"body": [{
        "id": "3",
        "externalId": "billgates",
        "status": "active",
        "createdAt": "2018-11-14T08:36:50.967Z",
        "updatedAt": "2018-11-14T08:36:50.967Z",
        "firstName": "yehu",
        "lastName": "da",
        "email": "bg@g.com"
    }
],
"headers": {
    "x-powered-by": "Express",
    "access-control-allow-origin": "*",
    "content-type": "application/json; charset=utf-8",
    "content-length": "189",
    "etag": "W/\"bd-Emx3/KChQLzf9+6bgFSHXPQgDTM\"",
    "date": "<<Masked>>",
    "connection": "close"
},
"request": {
    "uri": {
        "protocol": "http:",
        "slashes": true,
        "auth": null,
        "host": "mysite",
        "port": "4202",
        "hostname": "mysite",
        "hash": null,
        "search": "?username=billgates",
        "query": "username=billgates",
        "pathname": "/v1/users",
        "path": "/v1/users?username=billgates",
        "href": "http://mysite"
    },
    "method": "GET",
    "headers": {
        "Content-Type": "application/json",
        "accept": "application/json",
        "content-length": 2
    }
}
}

function findValue(obj, k, v) {
  let res = false

  if(!obj || typeof obj != "object") return false

  if (obj[k] == v) return true
  else {
	for (let [key, value] of Object.entries(obj)) {
          if(Array.isArray(value)) { res = res || value.some(d => findValue(d, k, v)) }
	  if(typeof value == "object") { res = res || findValue(value, k, v) }
    }
  }
  return res
}

console.log(findValue(object, 'externalId', 'billgates'))

console.log(findValue(object, 'lastName', 'da'))

console.log(findValue(object, 'x-powered-by', 'Express'))

console.log(findValue(object, 'externalId', 'Nitish'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多