Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I filter the values of an object

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"}'

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading