Answer the question
In order to leave comments, you need to log in
How to upload keys from JSON to html block attributes?
Kind.
There is a JSON like this:
{
"11" : {
"name" : "One",
"cost" : 10000,
"description" : "Bla"
},
"22" : {
"name" : "Two",
"cost" : 11000,
"description" : "Bla Bla"
},
"33" : {
"name" : "Three",
"cost" : 12000,
"description" : "Bla Bla Bla"
}
}
<div class="box">
<div class="item"></div>
</div>
<div class="box">
<div class="item"></div>
</div>
<div class="box">
<div class="item"></div>
</div>
<div class="box">
<div class="item" data-id="11"></div>
</div>
<div class="box">
<div class="item" data-id="22"></div>
</div>
<div class="box">
<div class="item" data-id="33"></div>
</div>
Answer the question
In order to leave comments, you need to log in
const myJson = `{
"11": {
"name": "One",
"cost": 10000,
"description": "Bla"
},
"22": {
"name": "Two",
"cost": 11000,
"description": "Bla Bla"
},
"33": {
"name": "Three",
"cost": 12000,
"description": "Bla Bla Bla"
}
}`;
const keys = Object.keys(JSON.parse(myJson)); //массив ключей
$('.box .item').each((index, item) => {
$(item).attr('data-id', keys[index]);
});
keysVal = Object.keys(object);
for(i in keysVal){
$(".item").eq(i).prop("data-id", keysVal[i])
}
var json= {.....};
[].map.call(document.querySelectorAll('.item'), function(i, ind) {
i.setAttribute("data-id", Object.keys(json)[ind]);
});
The easiest way is to bypass the JSON:
var json = { /*тут ваш JSON*/ };
var index = 0;
var root = getRoot() // функция, отдающая блок, в котором есть ваш HTML, объект jQuery
for (var p in json) {
if (json.hasOwnProperty(p)) {
//Получить див по индексу внутри контейнера, объект jQuery
var div = getDivByIndexFromRoot(root, index);
div.data('id', p);
}
}
getRoot
, getDivByIndexFromRoot
- fictitious functions, the behavior of which is described in the comments. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question