问题描述
我有一个JavaScript对象。
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)
这很好用。但是,如果我尝试获取Address.Name的属性值的值,
This works fine. But if I try to get the value of property value of "Address.Name" ,
喜欢: var dataToRetrieve =Address.Name;
显示 undefined
。
注意:属性变量由用户从HTML设置并且可以根据用户要求(他想要的属性值)进行更改。
Note : The property variable is set by user from HTML And it can be changed according to user requirement(which property value he wants).
我想要实现的目标:
1)如果 dataToRetrieve =Name
,它应该给我John
,
1) If dataToRetrieve = "Name"
, it should give me "John"
,
2)如果 dataToRetrieve =Id
,它应该给我100
,
2) If dataToRetrieve = "Id"
, it should give me "100"
,
3)如果 dataToRetrieve =Address.Name
,它应该给我班加罗尔
,
3) If dataToRetrieve = "Address.Name"
, it should give me "Bangalore"
,
4)如果 dataToRetrieve =Address.Id
,它应该给我1个
4) If dataToRetrieve = "Address.Id"
, it should give me 1
Plunkr这里:
Plunkr Here : PLUNKR
推荐答案
使用 方法
var obj = {
Id: "100",
Name: "John",
Address: {
Id: 1,
Name: "Bangalore"
}
}
function GetPropertyValue(obj1, dataToRetrieve) {
return dataToRetrieve
.split('.') // split string based on `.`
.reduce(function(o, k) {
return o && o[k]; // get inner property if `o` is defined else get `o` and return
}, obj1) // set initial value as object
}
console.log(
GetPropertyValue(obj, "Name"),
GetPropertyValue(obj, "Id"),
GetPropertyValue(obj, "Address.Name"),
GetPropertyValue(obj, "Address.Id"),
GetPropertyValue(obj, "Address.Idsd"),
GetPropertyValue(obj, "Addre.Idsd")
)
对于旧版浏览器,请检查。
这篇关于如何从javascript对象获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!