Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

jquery - How to get Property value from a Javascript object

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use reduce() method

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...