How to loop over an Array and find part that is included in the Item not the whole item?

Ratko Gjurichanin :

I am building a weather app so I need to grab the icon that is matching the call from API. I'm using parcel and parcel dumps all the images in dist folder. I import all the images and that gives me an object which I converted in a one dimensional Array. Because Parcel gives some extra text I can't grab the proper image. This is the array that I can see:

[0: "/01d.b9bbb2b9.svg" 1: "/01n.2290e7c6.svg" 2: "/02d.ac486e56.svg" 3: "/02n.259589cf.svg"]

<img src="${result.weather.icon}" alt="" class="weather--icon" />//I like to render it like this.

Is there a way I can loop over an array and get only the icon that is matching result.weather.icon ??? I need to find only the 01d or 02d from the array.

Fraser :

It isn't really clear what you are asking - because [0: "/01d.b9bbb2b9.svg" 1: "/01n.2290e7c6.svg" 2: "/02d.ac486e56.svg" 3: "/02n.259589cf.svg"] isn't a valid array.

However, presuming your array is simply the text elements then you can just use find. i.e.

let data = ["/01d.b9bbb2b9.svg", "/01n.2290e7c6.svg", "/02d.ac486e56.svg", "/02n.259589cf.svg"];

let result = data.find(x => x.startsWith('/01d'));

console.log(result);

Here find is better than filter as find returns the first value that matches from the collection. Once it matches the value in findings, it will not check the remaining values.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398343&siteId=1