Advertisements
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?
>Solution :
Please use reduce of Array
const array = ["info", "name"]
const object = {
id: 1,
info: {
name: "my name",
age: 21
}
}
const val = array.reduce((acc, item) => acc[item], object)
console.log(val)