javascript - 按键获取 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 路径吗?
解决方案
如果事情是动态的,程序化密钥搜索可能会有所帮助
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))
推荐阅读
- android - 如何在 Flutter 中运行函数和守护进程并在 StatefulWidget 中动态更改状态?
- sql - 从 Firebird 中的单个(单例)选择中分配多个参数?
- flutter - Flutter 在堆栈中心显示一个容器
- gcc - DPDK 使用 GCC 构建数组边界错误
- python-3.x - 在odoo 12中的product.tempate中写入attribute_line_ids
- c++ - 函数之前的 C++ 范围解析运算符
- api - Liferay 7.2 api json url 404
- google-sheets - 调试日期列 SQL 中的数值
- typescript - FeathersJS 生成器有错误吗?
- javascript - 如何在反应 redux 中从 api 发送响应数据?