3

I am sending an api call and retrieving data in json format.

$.getJSON(weatherAPI, function(data){
  // get data
});

If I call the object data and one of its properties (data.weather) I get the following outputs

[Object {
    description: "clear sky",
    icon: "xyz",
    main: "clear"
}]

I can't seem to use data.weather.description to get the desired output of "clear sky"

The whole json format data below

enter image description here

1
  • for loop weather Commented Dec 17, 2017 at 7:58

1 Answer 1

6

weather is an array of Objects, so you need to specify the index and access the property

 console.log(data.weather[0].description);

if you need to print all the element's value, use .foreach or .map()

.map() returns a new array while .forEach() doesn't. forEach() just operates on every value in the array. if you just need to console output the values use forEach.

using forEach,

data.weather.forEach((e) => {
  console.log(e.description);     
});

using .map

data.weather.map((e) => {
  console.log(e.description); 
  return e;    
});
Sign up to request clarification or add additional context in comments.

3 Comments

Canonically, you'd use .forEach(), not .map(), which wastes time creating and returning an array the same length as data.weather that you don't even use here.
why map, i know it serves the purpose here, but forEach is advisable for this use case.
@Nemani If OP wants to return , i have added that! thanks for the headsup

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.