0

This is my array

let result=[
  { lon: -122.08, lat: 37.39 },
  [ { id: 800, main: 'Clear', description: 'clear sky', icon: '01d' } ],
  'stations',
  {
    temp: 282.55,
    feels_like: 281.86,
    temp_min: 280.37,
    temp_max: 284.26,
    pressure: 1023,
    humidity: 100
  },
  16093,
  { speed: 1.5, deg: 350 },
  { all: 1 },
  1560350645,
  {
    type: 1,
    id: 5122,
    message: 0.0139,
    country: 'US',
    sunrise: 1560343627,
    sunset: 1560396563
  },
  -25200,
  420006353,
  'Mountain View',
  200
]

I want to fetch icon property, so I tried this

for (let i in result) {
    if (i == 1) {
        console.log(result[i]['icon']);
    }
}

But I got "undefined" as an output. please help me access the icon property in this array.

4
  • 1
    result[1][0].icon Simple Commented Sep 15, 2021 at 11:26
  • for...in... is for objects. result is an array. Commented Sep 15, 2021 at 11:28
  • Do you have multiple icons? Commented Sep 15, 2021 at 11:28
  • BTW ... how the array is filled is pretty unusual. The result items look like they are originally the values of an object's properties. Thus, if the object was known one hypothetically could write obj.<propertyName>[0].icon Commented Sep 15, 2021 at 11:47

1 Answer 1

1

It is not recommended to use for..in with arrays. As result is an array, then you can use index to fetch the icon property as:

result[1][0].icon

let result = [
  { lon: -122.08, lat: 37.39 },
  [{ id: 800, main: "Clear", description: "clear sky", icon: "01d" }],
  "stations",
  {
    temp: 282.55,
    feels_like: 281.86,
    temp_min: 280.37,
    temp_max: 284.26,
    pressure: 1023,
    humidity: 100,
  },
  16093,
  { speed: 1.5, deg: 350 },
  { all: 1 },
  1560350645,
  {
    type: 1,
    id: 5122,
    message: 0.0139,
    country: "US",
    sunrise: 1560343627,
    sunset: 1560396563,
  },
  -25200,
  420006353,
  "Mountain View",
  200,
];

const res = result[1][0].icon;

console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

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.