I need to build a JSON dynamically.
The JSON works if it is not dynamic.
Here is a working example but the "@id" and "name"are not dynamic :
var el_2 = document.createElement('script');
el_2.type = 'application/ld+json';
el_2.text = JSON.stringify({
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [{
"@type": "ListItem",
"position": 1,
"item": {
"@id": "https://example.com/",
"name": "Home",
}
}, {
"@type": "ListItem",
"position": 2,
"item": {
"@id": "https://example.com/text_1",
"name": "Text_1",
}
}, {
"@type": "ListItem",
"position": 3,
"item": {
"name": "Text_2",
}
}
}]
});
document.querySelector('head').appendChild(el_2);
I need to make it dynamic.
I use jQuery’s each() function to loop through each element of the breadcrumb.
Then, I push the element into an array:
var array_breadcrumb_text = [];
$('.region-breadcrumb .breadcrumb li').each(function(index, value) {
array_breadcrumb_text.push($(this).find("a").attr('href') + ' : ' + $(this).text());
// output of links and text is correct
console.log(array_breadcrumb_text[index]);
});
I don’t know how to use this array in order to build the JSON.
Generally, I use a foreach loop but since I am inside of the JSON.stringify(), I can't use a foreach loop, because I have a syntax issue.
Here is the breadcrumb HTML structure
<ol class="breadcrumb">
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/text_1">Text_1</a>
</li>
<li class="active">
Text_2
</li>
</ol>