来自json的javascript数组过滤器

时间:2017-02-02 14:06:07

标签: javascript json parsing filter

我的坏我删除了旧的东西

2 个答案:

答案 0 :(得分:0)

我拿出Ajax调用使其变得简单我为非活动服务器添加了新的ul并添加了新的列表项。

https://jsfiddle.net/0m2xs3ah/5/

$.each(response.results,function(index, value){
    if(value.status){
      $('#active-servers').append('<li>'+value.server+'</li>');
  }else{
    $('#inactive-servers').append('<li>'+value.server+'</li>');
  }

});

&#13;
&#13;
var response = {
"results": [
    {
        "server": "server04.republic-m.com",
        "status": true
    },
    {
        "server": "server06.republic-m.com",
        "status": true
    },
    {
        "server": "server06.republic-m.com",
        "status": true
    },
    {
        "server": "server17.republic-m.com",
        "status": false
    },
    {
        "server": "server18.republic-m.com",
        "status": true
    },
    {
        "server": "server20.republic-m.com",
        "status": true
    },
    {
        "server": "server21.republic-m.com",
        "status": false
    },
    {
        "server": "server25.republic-m.com",
        "status": true
    }
]
}

$.each(response.results,function(index, value){
	if(value.status){
  	  $('#active-servers').append('<li>'+value.server+'</li>');
  }else{
    $('#inactive-servers').append('<li>'+value.server+'</li>');
  }

});

var servers = response.results;
var onlineServers = servers.filter(function(server){
	if(server.status){
  	return (server.status == true);  
  }

});
var offlineServers = servers.filter(function(server){
	if(!server.status){
  	return (server.status == false);  
  }
});

console.log(offlineServers)
console.log(onlineServers)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span>Active</span>
  <ul id= "active-servers">

  </ul>
</div>

<div>
<span>Inactive</span>
  <ul id= "inactive-servers">

  </ul>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我认为你只需要一个if语句来选择div中的结果:

$(document).ready( function() {
    $.ajax({
        type: 'POST',
        url: 'servers',
        data: {results:'results', status:'status'},
        dataType: 'json',
        cache: false,
        success: function(response) {
            $('#active-servers, #inactive-servers').html('');
            $.each(response.results,function(index,result){
                if (result.status)
                    $('#active-servers').append('<li>'+result.server+'</li>');
                else
                    $('#inactive-servers').append('<li>'+result.server+'</li>');
            });
        }
    });
});