-1

What I want to do is filter two different values from an object so I can merge them

I need to find a way to merge only the keys with the same value in "artist" and with the same value in "Title"

I got the merge code from another question, so I don't know so much of what's happening there for me to make any change.

var data = '[{"title":"Better","artist":"Ben Platt","plays":"5"},{"title":"Better","artist":"OneRepublic","plays":"12"},{"title":"Honest Man","artist":"Ben Platt","plays":"23"},{"title":"Better","artist":"Ben Plat","plays":"9"}]';

obj = JSON.parse(data);

// turns the "plays" value into an integer
for (i = 0; i < obj.length; i++) {
  obj[i].plays = parseInt(obj[i].plays, 10);
}

// merge all the songs with the same name and sum the "plays" value
grouped = obj.reduce(function(hash) {
  return function(r, a) {
    (hash[a.name] = hash[a.title] || r[r.push({
      title: a.title,
      plays: 0
    }) - 1]).plays += a.plays;
    return r;
  };
}(Object.create(null)), []);

console.log(grouped);

The output I'm looking for would be something like this:

'[{"title":"Better","artist":"Ben Platt","plays":"14"},{"title":"Better","artist":"OneRepublic","plays":"12"},{"title":"Honest Man","artist":"Ben Platt","plays":"23"}'
Vitor
  • 3
  • 2

1 Answers1

0

const data = JSON.parse('[{"title":"Better","artist":"Ben Platt","plays":"5"},{"title":"Better","artist":"OneRepublic","plays":"12"},{"title":"Honest Man","artist":"Ben Platt","plays":"23"},{"title":"Better","artist":"Ben Platt","plays":"9"}]');

let grouped = {};
data.forEach(i=>(grouped[JSON.stringify([i.title,i.artist])]??=[]).push(i));
grouped = Object.values(grouped)
  .map(i=>({...i[0], plays: i.reduce((a,c)=>a+parseInt(c.plays), 0)}));

console.log(grouped);
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27