Reputation: 105
I have a json as follows -
{
"albums": {
"abc": "ABC",
"pqr": "PQR",
"lmn": "LMN",
"xyz": "XYZ"
}
}
In the html structure below, I want that each value in the json should be added in each subsequent p tag (in the same order)
<div>
<p><p>
<div>
<div>
<p><p>
<div>
<div>
<p><p>
<div>
<div>
<p><p>
<div>
(The divs are NOT be appended dynamically). I also don't want to pick each p tag and set value of each key to it one by one. I want this to happen automatically when I call the json ( which is stored in a separate file)
I am trying -
$(document).ready(function(){
$.getJSON("albums.json",
function (response) {
$.each(response.albums, function (key,value) {
$('p').each(function () {
$(this).html(value);
});
})
})
Doesn't give any output. Can anyone please tell me how to achieve this?
Thanks!!!
Upvotes: 0
Views: 30
Reputation: 2390
Your HTML isn't valid (none of <p>
or <div>
are closed).
let json = {
"albums": {
"abc": "ABC",
"pqr": "PQR",
"lmn": "LMN",
"xyz": "XYZ"
}
};
let i = 0;
$.each(json.albums, function (key,value) {
$(`p:eq(${i})`).html(value);
i++;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
Upvotes: 0
Reputation: 136094
You can do it by getting the index of the item from your values and using that to target the right <p>
:
var response = {
"albums": {
"abc": "ABC",
"pqr": "PQR",
"lmn": "LMN",
"xyz": "XYZ"
}
}
var $p = $('p');
Object.values(response.albums).forEach( (value,i) => {
$($p[i]).html(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
Upvotes: 1