Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get Object property by array of index

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading