So this original piece of code:
const imgUrls = {};
function onXhrLoad() {
const json = JSON.parse(this.response);
const photos = json.photos ? json.photos.photo : [json.photo];
for (const {id, url_o} of photos) {
imgUrls[id] = url_o;
}
}
The original code assumed that the biggest available url to an image in the object "photos" is "url_o", but sometimes that size is not available so I wanted to change the "url_o" in the last 2 lines to the biggest size available in "photos" using the array size (array "size" in the modified code is the order of sizes from biggest to smallest).
so I modified the code as follows:
const imgUrls = {};
const sizes = ['url_o', 'url_6k', 'url_5k', 'url_4k', 'url_3k', 'url_k', 'url_h', 'url_l'];
function onXhrLoad() {
const json = JSON.parse(this.response);
const photos = json.photos ? json.photos.photo : [json.photo];
for (var p of photos) {
for (var s of sizes) {
if (s in p) {
var url = p[s];
break;
}
}
const id = p.id;
imgUrls[id] = url;
}
}
As requested in a comment, there is an example response at this link.
In this response there is no url_o
, the biggest is url_6k
My question is if there is a better way to change the "url_o"
than going through two for loops and an if condition.
1 Answer 1
find the first "biggest" url size name. A more convenient way is using Array.prototype.find() method:
p.id
can be used directly as a key for objectimgUrls
- instead of generating constantconst id = p.id;
for eachp
(photo)
const imgUrls = {};
const sizes = ['url_o', 'url_6k', 'url_5k', 'url_4k', 'url_3k', 'url_k', 'url_h', 'url_l'];
function onXhrLoad() {
const json = JSON.parse(js);
const photos = json.photos ? json.photos.photo : [json.photo];
for (var p of photos) {
imgUrls[p.id] = p[sizes.find((s) => p[s])];
}
}
-
\$\begingroup\$ Thank you, that seems to do the trick. just to make sure I understand what you did correctly, does this mean that "sizes.find" will take the first entry of "sizes" name it "s" and check if it exists in "p", if it does, it will use that value of "s", if not it will move on to the next entry in "s" in order check again and keep on going and until it finds a match? \$\endgroup\$Adam– Adam2019年11月06日 09:32:03 +00:00Commented Nov 6, 2019 at 9:32
-
1\$\begingroup\$ @Vagabond, Yes, you got it right \$\endgroup\$RomanPerekhrest– RomanPerekhrest2019年11月06日 09:36:04 +00:00Commented Nov 6, 2019 at 9:36
responses
to your question to add more context? \$\endgroup\$