A
A
Alexey2014-11-12 13:00:46
JavaScript
Alexey, 2014-11-12 13:00:46

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
            }
        ]
    },.......

I need to count how many "likes" each user has.
That is:
For example, we take the first id == 0.
We go through the objects, which can be very many and look:
If id == 0 and like == 1, add +1 to the array.
As a result, I should get:
usersWithLikes[user id] = number of likes in all objects

usersWithLikes[0] = 3
usersWithLikes[1] = 1
usersWithLikes[2] = 4
usersWithLikes[3] = 0


At the moment I think like this:
thumbsUp_data - json data

var usersWithLikes = thumbsUp_data.map(function(user_data){
                    return user_data.users.filter(function(value){
                        return value.like == 1;
                    }).length;
                });


But this is not correct, because it counts how many likes there are in the object.
Help me decide...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2014-11-12
@azovl

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);

A
alvoro, 2014-11-12
@alvoro

var likes = users.reduce(function (likes, user) {
  user.users.forEach(function (user) {
    likes[user.id] = likes[user.id]|| 0;
    likes[user.id] += user.like;
  });
  return likes;
}, {});
console.log(likes)

This is hardly what you need, but the idea should be clear

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question