简体   繁体   中英

How to append from JSON after filter on key value

I have a JSON where I use a jQuery $.each function to append the data to a table. I do an if statement to check if a value matches a string.

In my last table column, I need to get data from another text filter. So if the data value matches my filter, then append it as the last td

dataset = [
  "river": {
    "year": "2016",
    "name": "Silver Creek",
    "series": "Caught fish",
    "weight": "100 kg",

  },
  "river": {
    "year": "2016",
    "name": "Silver Creek",
    "series": "Released fish",
    "weight": "60 kg"
  }
];

$(dataset).each(function(i, data){

  if (data.year === "2016" && data.series === "Caught fish") {
    $('tbody').append('<tr class="river"><td>' + this.year + '</td><td>' + this.name + </td><td>' + this.weight + </td></tr>')
  } if (data.year === "2016" && data.series === "Released fish") {
    $('tr.river').append('<td>' + this.weight + '</td>')
  }

});

The code above does not do but I want, but may be a hint of what I want to achieve.

What I need as a table row:

YEAR | NAME         | CAUGHT | RELEASED
2016 | Silver Creek | 100 kg | 60 kg

Any suggestions? Could I build a new variable based on the dataset outside the $.each function?

Use the :contains selector for released fish to see if the year and waterbody already exist in the table:

 var dataset = [ {"year": "2015","name": "Cedar Creek","series": "Caught fish","weight": "90 kg"}, {"year": "2016","name": "Silver Creek","series": "Caught fish","weight": "60 kg"}, {"year": "2015","name": "Cedar Creek","series": "Released fish","weight": "40 kg"}, {"year": "2016","name": "Silver Creek","series": "Released fish","weight": "60 kg"} ]; dataset.forEach(function(data) { if(data.series === 'Caught fish') { $('tbody').append('<tr class="river"><td>' + data.year + '<td>' + data.name + '<td>' + data.weight); } else { $('tr:contains(' + (data.year + data.name) + ')').append('<td>' + data.weight); } }); 
 tr > * {border: 1px solid #ddd;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr><th>YEAR<th>NAME<th>CAUGHT<th>RELEASED </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM