Home > OS >  Can I convert this into length all at once?
Can I convert this into length all at once?

Time:09-16

This is some part of the JSON. There are other data where the selected genre is book. Hence, I wanted to have an example of how to filter the Movie and count the length of the genre too.

const data = [{
      "1": { drama: { Comedy: true, Romance: true } },
      "2": {
        drama2: { Tragedy: true}
        others: "Dystopian",
      },
      id: "zaMR9TR7hNV3p3VFNumyNbXMto93",
      genre: {
        selected: "Movie",
      },
      displayName: "p1"
    }, 
     {
      "1": { drama: { Tragedy: true } },
      "2": {
        drama2: { Romance: true}
      },
      id: "zaMR9TR7hNV3p3VFNumyNbXMto93", //sample id
      genre: {
        selected: "Movie",
      },
      displayName: "p2"
    }]

 const drama = data.filter(
    (v) => v.genre?.selected == "Movie"
  )
  
  const comedy = drama.filter(
    (a) =>
    a["1"]?.drama.Comedy == true
  );

  const romance = drama.filter(
    (a) =>
    a["1"]?.drama.Romance == true
  );

   const tragedy = drama.filter(
        (a) =>
        a["1"]?.drama.Tragedy == true
      );

Is there a way where I could turn the comedy, romance, and tragedy into a length all at once rather than something like this?

  let n = comedy.length
  console.log(n)

CodePudding user response:

You can use Array.reduce to create an object, counts, containing the count for each genre.

const data = [{
  "1": { drama: { Comedy: true, Romance: true, BuddyComedy: false } },
  "2": {
    drama2: { Tragedy: true},
    others: "Dystopian",
  },
  id: "zaMR9TR7hNV3p3VFNumyNbXMto93",
  genre: {
    selected: "Movie",
  },
  displayName: "p1"
}, 
 {
  "1": { drama: { Tragedy: true } },
  "2": {
    drama2: { Romance: true}
  },
  id: "zaMR9TR7hNV3p3VFNumyNbXMto93", //sample id
  genre: {
    selected: "Movie",
  },
  displayName: "p2"
}]

const movies = data.filter(v => v.genre?.selected == "Movie");
const counts = movies.reduce((acc, cur) => {
    return Object.entries(cur["1"].drama).reduce((acc, [key,value]) => { 
        if (value) { 
            acc[key] = (acc[key] || 0)   1;
        }
        return acc;
    }, acc)
}, {})

console.log('Counts:', counts)

  • Related