I am looking to create a function that can retrieve a specific property of an object based on an array of property names
const getObjectProperty = (arr: string[], object: any) {
// This function should return the desired object property
}
Expected Outcome:
Let's assume we have this Object
const object = {
id: 1,
info: {
name: "my name",
age: 21,
home: {
city: "New York",
address: "Street Name"
}
},
}
getObjectProperty(["info", "name"], object) // Should return "my name"
getObjectProperty(["info", "name", "city"], object) // Should return "New York"
getObjectProperty(["id"], object) // Should return 1
getObjectProperty(["info", "salary"], object) // Should return undefined
What is the best approach to accomplish this task?