skip to Main Content

I’m stuck on something simple. The code below will give "3" as the result…however. I want to get three without having to explicitly know "New York"?

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Display object properties:</p>

<p id="demo"></p>

<script>
const person = {
  city: {"New York":3}
};

let txt = "";
for (let x in person) {
  txt += person[x]["New York"] + " ";  <----how to get 3 without "New York" explicitly stated
};

document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

How can I pull this off. I promise I’ll put this nested object question in my personal notes so I won’t forget it again.

2

Answers


  1. Object.values retrieves the values in an object as an array (omitting the keys). Since you only seem to have one key in the object city there will only be on value in that array (index 0), so you could do:

        const person = {
          city: { "New York": 3 }
        };
        
        console.log(Object.values(person.city)[0]);
    Login or Signup to reply.
  2. Without additional context, it’s unclear what you mean by the "New York" key changing. Assuming that the city object will always have one key and you need to extract the value of that key, you can iterate over the keys of the object using a for…in loop, and extract the value using the Object.values() method:

    const person = {
      city: {"New York": 3}
    };
    
    let txt = "";
    for (let x in person) {
      txt += Object.values(person[x])[0] + " ";
    }
    
    console.log(txt); // Output: 3
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search