Reputation: 798
In my React project I have a nested JSON and I want to get a key to the object as a string:
Assuming I have a JSON of
{
"section_1": {
"sub_1": {
"object_1": {
"property_1": {},
"property_2": {}
}
}
}
I want to import that JSON as a module and use nice autocompletion to select keys, but if I pass in
section_1.sub_1.object_1
I want to have "section_1.sub_1.object_1"
as an output.
Using Object.keys()
is not the answer, because
Object.keys(section_1.sub_1.object_1)
will give me ["property_1","property_2"]
Example:
import paths from './paths.json'
...
<MyComponent data-path={jsonObjectNameFunction(section_1.sub_1.object_1)} />
...
I want data-path="section_1.sub_1.object_1"
Upvotes: 0
Views: 227
Reputation: 37
I understand u want to get value from object base on path.
U can use lodash get value by path
Upvotes: -1
Reputation: 1074495
You'll need to pass in not just section_1.sub_1.object_1
but also the object to look within (let's call it obj
), like this;
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);
To implement someFunction
, we have to find the name/value pairs at each level that lead go obj
, something like this:
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;
}
Live Example:
"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;
}
Upvotes: 2