Answer the question
In order to leave comments, you need to log in
How to correctly calculate data in JSON?
The bottom line is this, I have a json file:
[
{
"id": 0,
"username": "Antony",
"users": [
{
"id": 1,
"like": 0
},
{
"id": 2,
"like": 1
},
{
"id": 3,
"like": 0
},
{
"id": 4,
"like": 1
}
]
},
{
"id": 1,
"username": "Janet",
"users": [
{
"id": 0,
"like": 0
},
{
"id": 2,
"like": 1
},
{
"id": 3,
"like": 1
},
{
"id": 4,
"like": 1
}
]
},.......
usersWithLikes[user id] = number of likes in all objects
var usersWithLikes = thumbsUp_data.map(function(user_data){
return user_data.users.filter(function(value){
return value.like == 1;
}).length;
});
Answer the question
In order to leave comments, you need to log in
var usersWithLikes = {};
thumbsUp_data.forEach(function(data) {
data.users.forEach(function(value) {
// Если переменная пуста, положим туда 0
usersWithLikes[value.id] = usersWithLikes[value.id] || 0;
// Прибавим лайк
usersWithLikes[value.id] += value.like;
});
});
// На выходе получился хеш. Если надо именно массив, можно сделать так:
usersWithLikes = Array.prototype.slice.call(usersWithLikes, 0);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question