lipenco
lipenco

Reputation: 1368

mapping Json data and adding data attr

I have a difficulty with mapping my my Json data. I would like to add data attr to each div with .name class. So as the result is like that:

<div class="name" data-key="sth"> sty</div>

Key can be got like that: ['streme'].key

here is my buggy JS:

function getExistingLinks() {
          $.post( "http://0.0.0.0:9292/api/links", function( data ) {
            var names = data.map(function (i) {
            return i['link'].name
            });
            var keys = data.map(function (i) {
            return i['link'].key
            });
            var container = document.querySelector(".link-names");
                names.forEach(function(name) {
                    var div = document.createElement('div');
                    div.innerHTML = name;
                    $('div').addClass("name");
                    // $('div').each( function(index) {
                           $('div')[index].data("key") = keys[index];
                       }
                    container.appendChild(div);
                });
       });  
      return false;   
    }

Upvotes: 0

Views: 104

Answers (4)

rajesh kakawat
rajesh kakawat

Reputation: 10896

try something like this

 $('.name').data('key') //will give you sth

Upvotes: 0

PDA
PDA

Reputation: 774

the preferred method is to only add to the DOM once, as adding to the DOM will cause a redraw on each.

psuedo code as not sure what name represents in your innerHTML:

var divs = []; for (var i, len = names.length; i < len; i++) { divs.push($(''+name+'').data("key", keys[i])); }

$container.append(divs);

http://codepen.io/jsdev/pen/2866265243563efd79cf05a5b12202b3

Upvotes: 0

Christophe
Christophe

Reputation: 28114

names.forEach(function(name,index) {
  var div = document.createElement('div');
  div.innerHTML = name;
  $(div).addClass("name");
  $(div).data("key") = keys[index];
});

You need to remove the quotes in the $() selector!

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

As per your comment, may be try doing like:

var i = 0;
names.forEach(function(name) {
    var div = document.createElement('div');
    div.innerHTML = name;
    $('div').addClass("name");
    $('div').data("key", keys[i]);
    container.appendChild(div);
    i++;
});

Upvotes: 0

Related Questions