How to get Property value from a Javascript object

22,872

Solution 1

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


For older browser check polyfill option of reduce method.

Solution 2

Use following function:

var obj = { Id: "100", Name: "John", 
            Address:  [{ Id:1, Name:"Bangalore" }, { Id:2, Name: "Mysore" } ] };

function GetPropertyValue(object, dataToRetrieve) {
    dataToRetrieve.split('.').forEach(function(token) {
      if (object) object = object[token];
    });
    
    return object;
}

console.log(
  GetPropertyValue(obj, "Address.0.Name"),
  GetPropertyValue(obj, "Address.1.Id"),
  GetPropertyValue(obj, "Name"),
  GetPropertyValue(obj, "Id"),
  GetPropertyValue(obj, "Unknown"),
  GetPropertyValue(obj, "Some.Unknown.Property")
);

Solution 3

 function GetPropertyValue(object,dataToRetrieve){
  var valueArray = dataToRetrieve.split(".");
  if (valueArray.length <= 1) {
    return object[valueArray];
  } else {
    var res;
    function browseObj(obj, valueArray, i) {
      if (i == valueArray.length)
        res = obj;
      else
        browseObj(obj[valueArray[i]], valueArray, i+1);
    }
    browseObj(object, valueArray, 0);
    return res;
  }
}

Solution 4

I had written a standard reusable Object method to access nested properties dynamically. It's like

Object.prototype.getNestedValue = function(...a) {
  return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};

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..

Object.prototype.getNestedValue = function(...a) {
  return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var props = ["Address","Name"],
      obj = { Id: "100", Name: "John", Address: {Id:1,Name:"Bangalore"} },
      val = obj.getNestedValue(...props);
console.log(val);
// or you can of course do statically like
      val = obj.getNestedValue("Address","Name");
console.log(val);

You can see getNestedValue() and it's twin setNestedValue() working at https://stackoverflow.com/a/37331868/4543207

Share:
22,872
Bimal Das
Author by

Bimal Das

I am a committed and hard working individual who enjoys a challenge. In addition to strong communication skills, I am able to work effectively in a team. I can also demonstrate advanced problem-solving skills and thrive under pressure. My drive and ambition ensure I am a valuable addition to any company.

Updated on July 09, 2022

Comments

  • Bimal Das
    Bimal Das almost 2 years

    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