简体   繁体   中英

Retrieve each value from a specific key with json

I would like to know if there is a way to get every values of "-temp" from the .json

{
  "weather":{
    "notes":{
      "cities":[
        {
          "-id":"scranton",
          "-temp":"17"
        },
        {
          "-id":"paris",
          "-temp":"16"
        },
        {
          "-id":"new york",
          "-temp":"18"
        }
      ]
    }
  }
}

How I tried to get it with JavaScript but that didn't work and I get undefined

data.weather.notes.cities['-temp']

How can I get every value of "-temp"?

You can use map :

const temps = data.weather.notes.cities.map(city => city["-temp"]);

console.log(temps); // ["17", "16", "18"]

Of course you can always access to them individually:

const { cities } = data.weather.notes;

console.log(cities[0]["-temp"]); // "17"

Or loop all of them:

for (let city of cities) {
  console.log("temperature in %s is %s°", 
    city["-id"], city["-temp"]
  );
}

Here is an example for inserting the city's temp into a new array:

const newArray= new Array();

data.weather.notes.cities
  .forEach(city => newArray.push(city['-temp'])) 

You could possibly iterate through all the cities and gather the "-temp" keys.

data.weather.notes.cities.forEach(function(element) {
 for (var em in element) {
    if (em == "-temp")
    {
      console.log(element[em])
    }
 }
});

@ZER0 answer is probably the best though.

 var data = { "weather":{ "notes":{ "cities":[ { "-id":"scranton", "-temp":"17" }, { "-id":"paris", "-temp":"16" }, { "-id":"new york", "-temp":"18" } ] } } }; for(var i in data.weather.notes.cities) { let city = data.weather.notes.cities[i]; console.log(city["-temp"]); //You_ can get it here }

You can't use JSON the same way you use jquery selectors. In your case, you need to map your array of cities.

const object = {
  "weather":{
    "notes":{
      "cities":[
        {
          "-id":"scranton",
          "-temp":"17"
        },
        {
          "-id":"paris",
          "-temp":"16"
        },
        {
          "-id":"new york",
          "-temp":"18"
        }
      ]
    }
  }
};

const tempList = object.weather.notes.cities.map(city => city['-temp']);

//result: ["17", "16", "18"]

See map documentation for further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM