i want create a function to get a property of an object based on an array of property name
const getObjectProperty = (arr: string[], object: any) {
// this function needs to return the object property
}
Expected Result:
Let’s say i have this Object
const object = {
id: 1,
info: {
name: "my name",
age: 21,
home: {
city: "New York",
address: "Street Name"
}
},
}
getObjectProperty(["info", "name"], object) // returns "my name"
getObjectProperty(["info", "name", "city"], object) // returns "New York"
getObjectProperty(["id"], object) // returns 1
getObjectProperty(["info", "salary"], object) // returns undefined
How can i achieve this?
2
Answers
Please use reduce of Array
You can get a property of an object based on an array of property names by using a for…of loop to iterate over the array of property names and access the corresponding properties of the object.
It could also be done with JavaScript’s reduce method in just one line
Note that this code assumes that the property names in the array exist within the object and follow a chain of nested properties. If any of the property names are misspelled or do not exist within the object, or if the property chain is broken, the code will throw an error.