distributing json array output to each
  • 2019-05-15 05:45发布

    I have a JSON output and i want to show each item inside each <li>.

    The JSON output looks like this:

    var data = [
    {
        "MachineID":"171914",
        "Cost":"13,642.41",
        "Currency":"PHP"
    },
    {
        "MachineID":"172233",
        "Cost":"1,367.73",
        "Currency":"PHP"
    },
    {
        "MachineID":"41116",
        "Cost":"2,608.20",
        "Currency":"PHP"
    },
    {
        "MachineID":"178077",
        "Cost":"1,517.04",
        "Currency":"PHP"},
    {
        "MachineID":"176430",
        "Cost":"20,876.72",
        "Currency":"PHP"
    }
    ]
    

    And my code is this:

    $.each(data, function(i, obj) {
        $.each(obj, function(i, val) {
          $('li').append(obj.MachineID); 
        });
    });
    

    Now the result shows like this:

       Foo 171914171914171914172233172233172233411164111641116178077178077178077176430176430176430
       Bar 171914171914171914172233172233172233411164111641116178077178077178077176430176430176430
    

    I may have overlooked something on jQuery.each call and I need only to show one MachineID per <li>, the output should be like this:

        Foo 171914
        Bar 172233
        Baz 41116
        Qux 178077
    

    and so on..

    标签: jquery json each
    2条回答
    forever°为你锁心
    2楼-- · 2019-05-15 06:33

    If these are existing li elements, the best way would be to select the li elements, iterate them, and use the index in the iteration to grab the data.

    $('li').slice(0,data.length)
           .each(function(i,el){
               $(this).append(data[i].MachineID);
           });
    

    I used .slice() so that if there are more li elements than data, it won't try to access non-existent data.

    Demo: http://jsfiddle.net/MYC4J/


    If the <li> elements do not yet exist, then you'd need to create them:

    var ul = $('ul');
    
    $.each(data,function(i,obj) {
        $('<li>',{text:obj.MachineID}).appendTo(ul);
    });
    

    Demo: http://jsfiddle.net/MYC4J/1/

    查看更多
    Ridiculous、
    3楼-- · 2019-05-15 06:47

    Because you go through each object and each property you append for every object 3 times the MashineId.

    You only need 1 $.each-loop and append the MashineId to the right li.

    Something like that:

    $.each(data, function(index, value){
       $("ul li:nth-child(" + (index+1) + ")").append(value.MashineId);
    });
    

    nth-child() selects the li (1-based index) and appends the MashineId. That is for the case that your MashineIds are simply added to the next li. Perhaps you need for your case another logic to find the right li.

    查看更多
    登录 后发表回答