xenurs
xenurs

Reputation: 449

filter by a key/value from json Array

here is my code, and i would like to only display items which has "assistance" as tag and no the other. I really don't know how can i do that.

function displayall(newid){
  $.ajax({
      url: "https://cubber.zendesk.com/api/v2/users/"+newid+"/tickets/requested.json",
      type: 'GET',
      cors: true,
      dataType: 'json',
      contentType:'application/json',
      secure: true,
      beforeSend: function (xhr) {
          xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
      },
      success: function (data){
        var sortbydate = data.tickets.sort(function(a,b){ return new Date(b.created_at)- new Date(a.created_at); });
        for (i = 0; i < data.tickets.length; i++) {

            var myticket = data.tickets[i];
            var mydate = data.tickets[i].created_at;
            var created = moment(mydate).format("MM-DD-YY");
            var mytitle = data.tickets[i].subject;
            var description = data.tickets[i].description;
            var status = data.tickets[i].status;
            var ticketid = data.tickets[i].id;
            var tag = data.tickets[i].tags[0];





$("#mylist").append('<li class="row col-md-12 listing" id="newlist" value="'+ticketid+'" onclick="ticketcontent('+ticketid+","+newid+')">'+ '<span class="class_'+status+' otherClasses">' + status + '</span>'+'<div class="identifiant fixed col-md-2">'+" #"+ ticketid +'</div>'+'<div class="identifiant col-md-2">'+tag+'</div>'+'<div class="identifiant col-md-4">'+mytitle +'</div>'+'<div class="identifiant datefixed col-md-2">'+created+'</div>'+'</li>');
        }
      }
    })
}

and if i do console.log(data.ticket[i]) this is what i get:

enter image description here

Upvotes: 0

Views: 70

Answers (2)

Matthew Herbst
Matthew Herbst

Reputation: 32013

What you're looking for is:

var filteredTickets = data.tickets.filter(function(ticket) {
  return ticket.tags.indexOf('assistance') >= 0;
});

Upvotes: 4

Ken Bellows
Ken Bellows

Reputation: 6942

Try using data.tickets.filter():

data.tickets = data.tickets.filter(function(ticket){
  return ticket.tags[0] === 'assistance';
});

Upvotes: 1

Related Questions