I
I
igix2017-09-30 10:52:49
JavaScript
igix, 2017-09-30 10:52:49

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"
  }

}

How to organize the unloading of keys (11, 22, 33) in a loop into the attributes of blocks with the item class:
<div class="box">
  <div class="item"></div>
</div>
<div class="box">
  <div class="item"></div>
</div>
<div class="box">
  <div class="item"></div>
</div>

To end up with something like this:
<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>

Thank you.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Slava Borodulin, 2017-09-30
@igix

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]);
    });

P
Petya Persianov, 2017-09-30
@Dr0nk

keysVal = Object.keys(object);
for(i in keysVal){
    $(".item").eq(i).prop("data-id", keysVal[i]) 
}

P
Pavel Kornilov, 2017-09-30
@KorniloFF

var json= {.....};
[].map.call(document.querySelectorAll('.item'), function(i, ind) {
  i.setAttribute("data-id", Object.keys(json)[ind]);
});

A
Alexander Kuznetsov, 2017-09-30
@DarkRaven

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.
Perhaps there are other, more elegant solutions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question