This question has already been answered:

First, the values ​​from the JSON array were "pulled out" by variables:

var login = data.login, name = data.name, avatar_url = data.avatar_url, bio = data.bio; 

and placed in HTML using javascript:

 $('#avatar').html(''); var avatarImg = '<img src=' + avatar_url + ' class="img-circle" >'; $('#avatar').append(avatarImg); $('#name').html(''); var name = '<span>' + name + '</span>'; $('#name').append(name); $('#login').html(''); var login = '<span>' + login + '</span>'; $('#login').append(login); $('#bio').html(''); if (bio == null) { var bio = '<a href="#">Add a bio</a>'; }else { var bio = '<p>' + bio + '</p>' } 

Everything works fine, but for optimization I wanted to use a function that would pull the value from data and put this value where it needed. For example:

 var templ = function (item) { var itemId = '#' + item; var itemData = data.item; $(itemId).html(''); var itemTypeTempl = '<span>' + itemData + '</span>'; $(itemId).append(itemTypeTempl); }; templ('login'); 

But var itemData = data.item does not return data.login as I would like. Tried var itemData = 'data.' + item var itemData = 'data.' + item - but returns the string "data.login" , and I need to pull the data.

Reported as a duplicate by Grundy , user194374, Denis , Mr. Black , Bald Jul 25 '16 at 4:39 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    You are incorrectly trying to extract a value from the data array using the item key. Try this

      var templ = function (item) { var itemId = '#' + item; var itemData = data[item]; $(itemId).html(''); var itemTypeTempl = '<span>' + itemData + '</span>'; $(itemId).append(itemTypeTempl); }; templ('login'); 

    and I would suggest simplifying

      var templ = function (item) { $('#' + item).html('<span>' + data[item] + '</span>'); }; templ('login'); 
    • I’m ashamed that I was so blunted ... Thank you! - Aleksandr