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.

7
  • Object.keys(divisions) would solve your problem Commented Jul 11, 2015 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? Commented Jul 11, 2015 at 18:25
  • Do you control this structure? If so, why have a key that can't be predicted? It defeats the purpose. Commented Jul 11, 2015 at 18:31
  • I don't control the structure - it's given to me by an API Commented Jul 11, 2015 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? Commented Jul 11, 2015 at 18:36

4 Answers 4

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Good summary of all the options. Most people forget that for in iterates over inherited properties that are enumerable as well.
@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?
@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.
@PatrickRoberts Thanks for the example here. As a beginner, it helps to see some script that is relevant to what I'm doing.
2
object.divisions[Object.keys(object.divisions)[0]].name

2 Comments

Awesome, this one worked well for me. I was unaware that Object.keys() worked with strings too. Thanks!
For more info see @Oriol's answer, you could use any of those
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.