Issue
I have a nested Object that I need to iterate. The object looks like this:
{
"Page1": {
"path": "/page1"
},
"Page2": {
"path": "/account/menu/page1"
},
"Page3": {
"items": {
"Subpage1": {
"path": "/account/menu/subpage1"
},
"Subpage2": {
"path": "/account/menu/subpage2"
},
"Subpage3": {
"path": "/account/menu/subpage3"
}
}
},
"Page4": {
"items": {
"Subpage4": {
"path": "/account/menu/subpage4"
},
"Subpage5": {
"path": "/account/menu/subpage5"
},
...
I need to get the name of the specific subpage, based on the path of the user.
For example. If the user is on the page /account/menu/subpage2
. I need to get the name Subpage2
.
What I did is the following:
const currentPageName = getPageName(this.props?.match?.params.menu); //This function gets the name of the current page (Subpage2)
const getThePageName = = path => Object.keys(jsonData).find(el => jsonData[el]?.items && jsonData[el]?.items[currentPageName]?.path === path)
console.log("getThePageName", getThePageName("/account/menu/subpage2")));
The result of the above is Page3
, but I need it to be Subpage2
. What am I doing wrong and how to fix it?
Solution
here is some piece of code
const jsonData = { "Page1": { "path": "/page1" }, "Page2": { "path": "/account/menu/page1" }, "Page3": { "items": { "Subpage1": { "path": "/account/menu/subpage1" }, "Subpage2": { "path": "/account/menu/subpage2" }, "Subpage3": { "path": "/account/menu/subpage3" } } }, "Page4": { "items": { "Subpage4": { "path": "/account/menu/subpage4" }, "Subpage5": { "path": "/account/menu/subpage5" }, } } };
const currentPageName = 'Subpage2';
const getThePageName = path => Object.keys(jsonData).reduce((acc, el) => {
if (acc?.length) {
return acc;
}
if (jsonData[el].hasOwnProperty('items')) {
if (jsonData[el]?.items?.[currentPageName]?.path === path) {
console.log(path, jsonData[el]?.items?.[currentPageName]?.path)
acc = currentPageName;
}
} else {
if (jsonData[el].path === path) {
console.log(path, jsonData[el].path, path)
acc = el;
}
}
return acc;
}, undefined);
console.log("getThePageName", getThePageName("/account/menu/subpage2"));
Answered By – Mohit Sharma
Answer Checked By – Candace Johnson (BugsFixing Volunteer)