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.
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.