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>

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

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

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;


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.

>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

Leave a Reply