2

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?

Andreas Hunter
  • 4,504
  • 11
  • 65
  • 125
  • Why not directly accessing the object (e.g., `user.details.age`)? – Arik Jun 14 '20 at 07: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 – Andreas Hunter Jun 14 '20 at 08:04
  • You can use "optional chaining" like so: eval("user?." + "details.education.university".replace(/\./g, '?.')) – Arik Jun 14 '20 at 08:14

1 Answers1

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;
}
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54