I have a little problem sorting JSON.
So here is my JSON data:
[
{
nom: "TERRES LATINES",
numero: "0473343687",
image: "http://s604712774.onlinehome.fr/bonapp/api/wp-content/uploads/2016/12/IMG_1165.jpg",
timedate: "30/6/2017 - 7:5:45"
},
{
nom: "TERRES LATINES",
numero: "0473343687",
image: "http://s604712774.onlinehome.fr/bonapp/api/wp-content/uploads/2016/12/IMG_1165.jpg",
timedate: "30/6/2017 - 7:5:45"
},
{
nom: "LE FURCO",
numero: "0473156551",
image: "http://s604712774.onlinehome.fr/bonapp/api/wp-content/uploads/2016/12/IMG_0843.jpg",
timedate: "30/6/2017 - 18:4:6"
},
{
nom: "A L’IDEE",
numero: "0473193488",
image: "http://s604712774.onlinehome.fr/bonapp/api/wp-content/uploads/2016/12/IMG_0299.jpg",
timedate: "30/6/2017 - 23:5:56"
}
]
With this Ajax jQuery code I can call all the entries in a table:
$.ajax({
type: "GET",
url: 'http://s604712774.onlinehome.fr/bonapp/app/text.json',
dataType: 'json',
success: function(data) {
data.forEach(function(post) {
$( '#contenttableau' ).append( '<tr><td>' + post.nom + '</td><td>' + post.numero + '</td><td>' + post.timedate + '</td><td></td></tr>' );
});
}
});
How can I get the number of time TERRES LATINES is present like in the following?
Create a map that holds the count for each key, and append it with the other values, something like
$.ajax({
type : "GET",
url : 'http://s604712774.onlinehome.fr/bonapp/app/text.json',
dataType : 'json',
success : function(data) {
var map = {};
data.forEach(function(post) {
var key = post.numero;
if ( key in map ) {
map[key]++;
} else {
map[key] = 1;
}
});
data.forEach(function(post) {
var td1 = $('<td />', {html : post.nom}),
td2 = $('<td />', {html : post.numero}),
td3 = $('<td />', {html : post.timedate}),
td4 = $('<td />', {html : map[post.numero]}),
tr = $('<tr />');
$( '#contenttableau' ).append( tr.append(td1, td2, td3, td4) );
});
}
});
Something like:
let counts = {}
data.forEach(function(obj) {
counts[obj.nom] = (counts[obj.nom] || 0) + 1
})
let output = []
for(let nom in counts) {
output.push([nom,counts[nom]].join(' '))
}
document.querySelector('output').innerHTML = ['<ul>', '<li>', output.join('</li><li>'), '</li>', '</ul>'].join('')