Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get nested object value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading