Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
Check if my object contains one or more objects

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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" ]
about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!