Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing properties of a variable object with JavaScript

Tags:

javascript

I have a js object that looks like this:

 var object = {
      "divisions": {
          "ocd-division/country:us": {
              "name": "United States",
          }
      }
    };

I want to access the property listed under the nested object "ocd-division/country:us" (aka "name"), but the problem I'm having is that "ocd-division/country" is a variable object. Like it might be ":can" for Canada or something.

My question is, can I still access the name property under that object even though it's variable? I wrote the code I came up with below, but it calls the object literally, so it can't account for a change in the object's name.

    var country = document.getElementById("p");
    p.innerHTML = object.divisions["ocd-division/country:us"].name;

I'm new to JavaScript so I'm sorry if this is a dumb question.

like image 238
brohannsebastian Avatar asked Jul 11 '15 18:07

brohannsebastian


1 Answers

When you don't know the properties of an object, you can use

  • for...in loop

    It iterates enumerable own and enumerable inherited properties.

  • Object.keys

    It returns an array which contains enumerable own properties.

  • Object.getOwnPropertyNames

    It returns an array which contains own properties.

// Adding properties: "ownEnumerable", "ownNonEnumerable",
// "inheritedEnumerable" and "inheritedNonEnumerable"
var obj = Object.defineProperties({}, {
  ownEnumerable: {enumerable: true},
  ownNonEnumerable: {},
});
Object.defineProperties(Object.prototype, {
  inheritedEnumerable: {enumerable: true},
  inheritedNonEnumerable: {},
});

// Display results
function log(id, arr) {
  document.getElementById(id).textContent = '[' + arr.join(', ') + ']';
}
log('forin', function(forInProps){
  for (var prop in obj) forInProps.push(prop);
  return forInProps;
}([]));
log('keys', Object.keys(obj));
log('names', Object.getOwnPropertyNames(obj));
<dl>
  <dt><code>for...in</code></dt><dd id="forin"></dd>
  <dt><code>Object.keys</code></dt><dd id="keys"></dd>
  <dt><code>Object.getOwnPropertyNames</code></dt><dd id="names"></dd>
</dl>
like image 143
Oriol Avatar answered Oct 02 '22 14:10

Oriol