Given an object like this:
const spacing = {
xxs: "0.25rem",
xs: "0.5rem",
sm: "0.75rem",
md: "1rem",
lg: "1.5rem",
"2xl": "2rem",
"3xl": "3rem",
oggetto: {
"1": 1,
"2": 2,
},
}
I'm trying to write a function that loops through my object, and checks if the property of this object is another nested object, like oggetto. In that case, I'd like to recursively call the function. My main goal is to retrieve all the keys of the main and any nested object. I'd share some code but I don't really have an idea on how to approach this. Thank you!
function getObjectKeys(o, keys = []) {
Object.entries(o).forEach(([key, value]) => {
if (typeof value === "object") {
getObjectKeys(value, keys);
} else {
keys.push(key);
}
});
return keys;
}
getObjectKeys(spacing); // [ "xxs", "xs", "sm", "md", "lg", "2xl", "3xl", "1", "2" ]
first you must consider arrays when using typeof since typeof of an array and an object both return 'object'.
then you can have a recursive function to loop through the keys and return them if they hold an object.
for example something like this will return an array of arrays which hold the object key in the first index and full path to access the object in the second index:
const obj = {
n: 1,
s: 'test',
b: false,
a: [],
obj1: {
n: 2
},
obj2: {
innerObj: {
b: true,
otherInnerObj: {
s: 'hi'
},
},
a: []
},
obj3: {}
};
function findObjects(obj, parent, pathArr = []) {
for (k in obj) {
const v = obj[k];
if (typeof v === 'object' && !Array.isArray(v)) {
const parentName = `${parent}/${k}`;
pathArr.push([k, parentName]);
findObjects(v, parentName, pathArr);
}
}
return pathArr;
}
const result = findObjects(obj, 'obj');
const onlyKeys = result.map(x => x[0]);
const onlyPaths = result.map(x => x[1]);
console.log(onlyKeys);
console.log(onlyPaths);
console.log(result);