How to get Property value from a Javascript object

僤鯓⒐⒋嵵緔 提交于 2019-11-30 10:14:33

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.

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")
);
 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;
  }
}
Redu

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!