簡體   English   中英

如何在嵌套的 json 文件中查找節點的深度?

[英]How to find depth of nodes in a nested json file?

我找到了許多解決方案來查找嵌套 json 文件中的節點深度。 但是當它設置最大遞歸限制時它拋出一個錯誤“最大遞歸深度超出”,它說“進程超出了一些錯誤代碼”作為我問題的一部分,我還需要找出 json 中每個節點的鍵名文件。

例如 json:

 "attachments": { "data": [ { "media": { "image": { "height": 400, "src": "https://scontent.xx.fbcdn.net/v/t1.0-1/10250217_10152130974757825_8645405213175562082_n.jpg?oh=904c1785fc974a3208f1d18ac07d59f3&oe=57CED94D", "width": 400 } }, "target": { "id": "74286767824", "url": "https://www.facebook.com/LAInternationalAirport/" }, "title": "Los Angeles International Airport (LAX)", "type": "map", "url": "https://www.facebook.com/LAInternationalAirport/" } ] }

output 應該是:

節點:[數據[媒體[圖像[高度,寬度,src]],目標[id,url],標題,類型,url]]

深度:4

如果其他人來到這里並發現接受的答案不起作用,因為字符串的 Object.keys() 返回字符串的每個字符的數組,因此對於大對象或具有大字符串的對象,它只會失敗。 這是有用的東西->

function getDepth(obj){
    if(!obj || obj.length===0 || typeof(obj)!=="object") return 0;
    const keys = Object.keys(obj);
    let depth = 0;
    keys.forEach(key=>{
        let tmpDepth = getDepth(obj[key]);
        if(tmpDepth>depth){
            depth = tmpDepth;
        }
    })
    return depth+1;
}

示例 - https://jsfiddle.net/95g3ebp7/

請嘗試以下 function:


 const getDepth = (
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  obj: Record<string, any>,
  tempDepth?: number
): number => {
  let depth = tempDepth ? tempDepth : 0;
  if (obj !== null) {
    depth++;
    if (typeof obj === 'object' && !Array.isArray(obj)) {
      const keys = Object.keys(obj);
      if (keys.length > 0)
        depth = Math.max(
          ...keys.map((key) => {
            return getDepth(obj[key], depth);
          })
        );
    } else if (Array.isArray(obj)) {
      if (obj.length > 0)
        depth = Math.max(
          ...obj.map((item) => {
            return getDepth(item, depth);
          })
        );
    }
  }
  return depth;
};

如果你嘗試這個,我相信你必須得到7


  console.log(getDepth({
    a: {
      b: { a: [{ a: { a: [] } }] }
    }
  }));

function geth(obj) {
  var depth = 0;
  var k = Object.keys(obj);
  console.log(k);
  for (var i in k) {
      var tmpDepth = geth(obj[k[i]]);
      if (tmpDepth > depth) {
          depth = tmpDepth
      }
  }
  return 1 + depth;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM