skip to Main Content

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


  1. 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)
    Login or Signup to reply.
  2. 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.

    const array = ["info", "name"];
    
    const object = {
     id: 1,
     info: {
     name: "my name",
     age: 21
     }
    };
    
    let result = object;
    
    for (const property of array) {
      result = result[property];
    }
    
    console.log(result); // "my name"
    

    It could also be done with JavaScript’s reduce method in just one line

    const result= array.reduce((result, value) => result[value], object)
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search