5

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.

  • `Object.keys(divisions)` would solve your problem – vinayakj Jul 11 '15 at 18:18
  • How you deciding wheather I want "ocd-division/country:us" or something else?Ans this object structure is the same for all country? – RIYAJ KHAN Jul 11 '15 at 18:25
  • Do you control this structure? If so, why have a key that can't be predicted? It defeats the purpose. – Lye Fish Jul 11 '15 at 18:31
  • I don't control the structure - it's given to me by an API – brohannsebastian Jul 11 '15 at 18:34
  • Is it possible that there will be multiple items under the `divisions` object? If so, do you need to get all of them, or do you need to pick out specific ones? – Lye Fish Jul 11 '15 at 18:36
  • @Lye Fish Yes, there are multiple items under the divisions object, and it's possible I will need to pick out specific ones in the very near future. I just omitted that part as of right now for the sake of brevity – brohannsebastian Jul 11 '15 at 18:40
  • @RIYAH KHAN - Sorry I missed this comment in the beginning. That information is given to me by an api, and I'm not entirely sure that structure will be the same for all countries. – brohannsebastian Jul 11 '15 at 18:43

4 Answers4

7

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>
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 1
    Good summary of all the options. Most people forget that `for in` iterates over inherited properties that are enumerable as well. – Patrick Roberts Jul 11 '15 at 18:32
  • @Oriol would it be okay if I add an edit that demonstrates these three options on an object with own and inherited properties, both enumerable and non-enumerable? – Patrick Roberts Jul 11 '15 at 18:43
  • @PatrickRoberts Yes, adding an example was a good idea, I have included it. Feel free to edit if you had in mind a shorter or clearer example. – Oriol Jul 11 '15 at 21:52
  • @PatrickRoberts Thanks for the example here. As a beginner, it helps to see some script that is relevant to what I'm doing. – brohannsebastian Jul 13 '15 at 19:19
2
object.divisions[Object.keys(object.divisions)[0]].name
vinayakj
  • 5,591
  • 3
  • 28
  • 48
1

Sure...

for (var division in object.divisions) {
    var name = object.divisions[division].name;
    // Do what you want with name here
}

If the object has prototype methods you will want to use Object.prototype.hasOwnProperty() to ensure they don't get iterated like so:

for (var division in object.divisions) {
    if (!object.divisions.hasOwnProperty(division)) continue;
    var name = object.divisions[division].name;
    // Do what you want with name here
}

Or use Object.keys() if you don't care about IE8 support and iterate over those.

Object.keys(object.divisions).forEach(function(division) {
    var name = object.divisions[division].name;
    // Do what you want with name here
});

EDIT: Upon re-reading your question it occurs to me that you may already know the key name but want to access the object with a variable key name, which is also absolutely fine:

var division = 'ocd-division/country:us';
object.divisions[division].name;

When using [] bracket notation to access an object you can insert any code that evaluates to a string, you could even call a function in there that returns a string.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

George Reith
  • 13,132
  • 18
  • 79
  • 148
0

You can iterate through object using for loop.

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

Here is the for loop

for(var a in obj){ //loop first the object
  for(var b in obj[a]){ // then second object (divisions)
    for(var c in obj[a][b]){ //then third object (ocd-division/country:us)
      if(c == 'name'){ //c is the key of the object which is name
        console.log(obj[a][b][c]); //print in console the value of name which is United States.
        obj[a][b][c] = "Canada"; //replace the value of name.
        var objName = obj[a][b][c]; //or pass it on variable. 
      }
    }
  }
}

console.log(obj); //name: Canada
console.log(objName); //name: United States

You can also use this reference:
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Statements/for
http://stackoverflow.com/questions/8312459/iterate-through-object-properties
DevBert
  • 149
  • 2
  • 8