I have an array with urls called "urls" that i want to match with the url on another array called "arrayConst" and then apply the header and the image that correspond to that url in my if-statement but this code seems only to apply the first header on index[0] instead of the header that correspond to that url. What am i doing wrong?
let findRecentPosts = setInterval(function () {
const arrayConst = [
{
header: "XYZ",
url: "url1",
image: "url(https://....jpg)",
},
{
header: "ABC",
url: "url2",
image: "url(https://....jpg)",
},
];
const urls = ["url1", "url2", "url3"];
if ($(".l-blog__sidebar").length > 0) {
clearInterval(findRecentPosts);
$(".c-related-single").each(function (i) {
$(this).find("a").attr("href", urls[i]);
$(this).find(".c-related-single__header").text(arrayConst[i].header);
$(this).find(".c-related-single__image .c-background-image").css("background-image", arrayConst[i].image);
});
}
}, 1000);
$(document).ready(function () {
setTimout(function () {
clearInterval(findRecentPosts);
}, 5000);
});
CodePudding user response:
You can use find
method of array to find the element from the other array.
let findRecentPosts = setInterval(function () {
arrayConst = [
{
header: "XYZ",
url: "https...",
image: "url(https://....jpg)",
},
{
header: "ABC",
url: "https...",
image: "url(https://....jpg)",
},
];
const urls = ["url1", "url2", "url3"];
if ($(".l-blog__sidebar").length > 0) {
clearInterval(findRecentPosts);
$(".c-related-single").each(function (i) {
const url = urls[i];
const otherURLProperties = arrayConst.find((u) => u.url === url); // returns the matching element
$(this).find("a").attr("href", url);
$(this).find(".c-related-single__header").text(otherURLProperties.header);
$(this).find(".c-related-single__image .c-background-image").css("background-image", otherURLProperties.image);
});
}
}, 1000);
$(document).ready(function () {
setTimout(function () {
clearInterval(findRecentPosts);
}, 5000);
});