Property in javascript object

2

How can I make a check in an array of objects where the intention would be to delete the duplicates however, do I need to add the values of a property?

Example: I have an array of objects:

musicas = [{nome: 'Música 1', clicks: 1}, {nome: 'Música 1', clicks: 1}]

I need to return a new array from this without repeating the songs but adding the total number of clicks.

Something that looks like this:

musicas = [{nome: 'Música 1', clicks: 2}]
    
asked by anonymous 06.12.2015 / 23:26

1 answer

3

I suggest you iterate this array and create an object at the same time. So you have the name of the song in common and you will add the clicks.

Something like this:

var musicas = [{nome: 'Musica 1', clicks: 1}, {nome: 'Musica 1', clicks: 1}];

var res = {};
musicas.forEach(function(musica){
    if (!res[musica.nome]) res[musica.nome] = musica; // se ainda não estiver registada
    else res[musica.nome].clicks++; // já existe, somar o click
});
console.log(JSON.stringify(res)); // {"Musica 1":{"nome":"Musica 1","clicks":2}}

// e se quiseres isso de volta numa array
var array = Object.keys(res).map(function(mus){
    return res[mus];
});

console.log(JSON.stringify(array)); // [{"nome":"Musica 1","clicks":2}]

jsFiddle: link

    
06.12.2015 / 23:33