我有一个JavaScript对象。

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”属性值的值,

像:var dataToRetrieve = "Address.Name"; 它显示undefined

注意:该属性变量由用户从HTML设置,可以根据用户要求(他想要的属性值)进行更改。

我要实现的目标:

1)如果是dataToRetrieve = "Name",应该给我"John"

2)如果是dataToRetrieve = "Id",应该给我"100"

3)如果是dataToRetrieve = "Address.Name",应该给我"Bangalore"

4)如果是dataToRetrieve = "Address.Id",应该给我1

在这里Plunkr:PLUNKR

最佳答案

使用 reduce() 方法

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")
)



对于较旧的浏览器,请检查polyfill option of reduce method

08-08 05:58