首页 > 解决方案 > 按键获取 JSON 对象的路径?

问题描述

给定以下对象:

const ourObject = {
    "payload": {
        "streams": [
            {
                "children": {
                    "2165d20a-6276-468f-a02f-1abd65cad618": {
                        "additionalInformation": {
                            "narrative": {
                                "apple": "A",
                                "banana": "B"
                            },
                            "myInventory": {
                                "fruits": [
                                    {
                                        "name": "apple"
                                    },
                                    {
                                        "name": "banana"
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        ]
    }
};

我们正在尝试找到 的路径myInventory,问题是孩子的 uuid 每次都会不同。知道我们如何myInventory通过提供它作为键来获取路径并获取它的 json 路径吗?

标签: javascriptarraysjsonlodash

解决方案


如果事情是动态的,程序化密钥搜索可能会有所帮助

const ourObject = {
    "payload": {
        "streams": [
            {
                "children": {
                    "2165d20a-6276-468f-a02f-1abd65cad618": {
                        "additionalInformation": {
                            "narrative": {
                                "apple": "A",
                                "banana": "B"
                            },
                            "myInventory": {
                                "fruits": [
                                    {
                                        "name": "apple"
                                    },
                                    {
                                        "name": "banana"
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        ]
    }
};

const getPath = (key, o) => {
  if (!o || typeof o !== "object") {
    return "";
  }

  const keys = Object.keys(o);
  for(let i = 0; i < keys.length; i++) {
    if (keys[i] === key ) {
      return key;
    }
    
    const path = getPath(key, o[keys[i]]);
    if (path) {
      return keys[i] + "." + path;
    }
  }
  return "";
};

const getValueForKey = (key, o) => {
  if (!o || typeof o !== "object") {
    return undefined;
  }

  const keys = Object.keys(o);
  for(let i = 0; i < keys.length; i++) {
    if (keys[i] === key ) {
      return o[key];
    }
    
    const value = getValueForKey(key, o[keys[i]]);
    if (value) {
      return value;
    }
  }
  return undefined;
}

console.log(getPath("myInventory", ourObject))
console.log(getValueForKey("myInventory", ourObject))


推荐阅读