JSON - 如何获取对象"path"



在我的React项目中,我有一个嵌套的JSON,我想获得一个字符串形式的对象键:

假设我有的JSON

{
"section_1": {
"sub_1": {
"object_1": {
"property_1": {},
"property_2": {}
}
}
}

我想将JSON作为一个模块导入,并使用漂亮的自动完成来选择键,但如果我传入section_1.sub_1.object_1我想要"section_1.sub_1.object_1"作为输出。

使用Object.keys()不是答案,因为Object.keys(section_1.sub_1.object_1)会给我["property_1","property_2"]

示例:

import paths from './paths.json'
...
<MyComponent data-path={jsonObjectNameFunction(section_1.sub_1.object_1)} />
...

我想要data-path="section_1.sub_1.object_1"

您不仅需要传入section_1.sub_1.object_1,还需要传入要查看的对象(我们称之为obj(,如下所示;

const obj = /*the import resulting in:*/{
"section_1": {
"sub_1": {
"object_1": {
"property_1": {},
"property_2": {}
}
}
};
someFunction(obj, obj.section_1.sub_1.object_1);

为了实现someFunction,我们必须在每个级别上找到导致obj的名称/值对,类似于以下内容:

function someFunction(container, target, path = "") {
for (const [key, value] of Object.entries(container)) {
const possiblePath = path ? path + "." + key : key;
if (value === target) {
return possiblePath;
}
if (value && typeof value === "object") {
const found = someFunction(value, target, possiblePath);
if (found) {
return found;
}
}
}
return null;
}

实例:

"use strict";
const obj = /*the import resulting in:*/{
"section_1": {
"sub_1": {
"object_1": {
"property_1": {},
"property_2": {}
}
}
}
};
console.log(someFunction(obj, obj.section_1.sub_1.object_1));
function someFunction(container, target, path = "") {
for (const [key, value] of Object.entries(container)) {
const possiblePath = path ? path + "." + key : key;
if (value === target) {
return possiblePath;
}
if (value && typeof value === "object") {
const found = someFunction(value, target, possiblePath);
if (found) {
return found;
}
}
}
return null;
}

我知道你想从基于路径的对象中获取值。

U可以使用lodash通过路径获取值

最新更新