What's the method for extracting object property names in JavaScript?

I’m trying to figure out how to get a list of property names from an object in JavaScript. Here’s what I’m working with:

let person = {
  fullName: 'Jane Doe',
  details: {
    years: 25,
    firstName: 'Jane'
  }
};

What I want is to end up with an array that looks like this:

let propertyList = ['years', 'firstName'];

Is there a built-in function or a simple way to do this? I’ve been scratching my head over this for a while now. Any help would be great!

I’ve faced this exact issue before, and Object.keys() is indeed the go-to solution. However, if you’re dealing with deeper nested objects or want more flexibility, you might want to look into Object.entries() as well. It returns an array of a given object’s own enumerable string-keyed property [key, value] pairs.

For your specific case:

const propertyList = Object.keys(person.details);

This will give you exactly what you’re looking for. If you need to go deeper or handle more complex scenarios, you could create a recursive function to traverse the object. But for most use cases, Object.keys() should suffice.

Just remember, it only returns enumerable properties. If you need non-enumerable ones too, Object.getOwnPropertyNames() might be worth exploring.

hey liam, object.keys() does the trick. for nested objects, try:

object.keys(person.details)

this returns an array of keys. hope it helps!

Object.keys() is indeed the standard approach, but there’s another method worth considering: for…in loop. It can be useful, especially when dealing with inherited properties:

let propertyList = [];
for (let prop in person.details) {
    if (person.details.hasOwnProperty(prop)) {
        propertyList.push(prop);
    }
}

This method allows you to filter properties if needed. The hasOwnProperty() check ensures you’re only getting the object’s own properties, not those inherited from its prototype chain. It’s slightly more verbose than Object.keys(), but offers more control in certain scenarios. Just something to keep in your toolkit alongside the other methods mentioned.