I have a JavaScript object.
var obj = { Id: "100", Name: "John", Address: {Id:1,Name:"Bangalore"} }
var dataToRetrieve= "Name";
function GetPropertyValue(object,dataToRetrieve){
return obj[dataToRetrieve]
}
var retval = GetPropertyValue(obj,dataToRetrieve)
This works fine. But if I try to get the value of property value of "Address.Name" ,
Like : var dataToRetrieve = "Address.Name";
it shows undefined
.
Note : The property variable is set by user from HTML And it can be changed according to user requirement(which property value he wants).
What I want to achieve :
1) If dataToRetrieve = "Name"
, it should give me "John"
,
2) If dataToRetrieve = "Id"
, it should give me "100"
,
3) If dataToRetrieve = "Address.Name"
, it should give me "Bangalore"
,
4) If dataToRetrieve = "Address.Id"
, it should give me 1
Plunkr Here : PLUNKR
Use following function:
I had written a standard reusable Object method to access nested properties dynamically. It's like
It will take dynamic arguments for the nested properties. If they are string type they are object properties if number type then they are array indices. Once you have this, your job becomes very easy. Let's see..
You can see
getNestedValue()
and it's twinsetNestedValue()
working at https://stackoverflow.com/a/37331868/4543207Use
reduce()
methodFor older browser check polyfill option of reduce method.