3

I have custom object

var user = {
  name: "John",
  lastname: "Doe",
  details: {
    age: 33,
    gender: "male",
    education: {
      university: "Oxford"
    }
  }
}

Now I need to function which can parse object key from string. E.g function args:

getObjectKeyValue("details.age") // 33
getObjectKeyValue("details.education.university") // Oxford

How can be realised like this function to get object key value from string dots based key?

3
  • Why not directly accessing the object (e.g., user.details.age)? Commented Jun 14, 2020 at 7:57
  • This objects passed on translation file and translation strings has dynamic params which must be defined on function arguments. E.g translation string Welcome ${username} to our website @Arik Commented Jun 14, 2020 at 8:04
  • You can use "optional chaining" like so: eval("user?." + "details.education.university".replace(/\./g, '?.')) Commented Jun 14, 2020 at 8:14

1 Answer 1

5

There will be better solution but you can try this

var user = {
  name: "John",
  lastname: "Doe",
  details: {
    age: 33,
    gender: "male",
    education: {
      university: "Oxford"
    }
  }
}

console.log(getObjectKeyValue("details.age"))
console.log(getObjectKeyValue("details.education.university"))

function getObjectKeyValue(param){
 var params=param.split(".");
 var obj=user
 params.forEach(el=>{
    obj=obj[el]
 })
 return obj;
}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.