Only display objects inside of an array with certain type [GRAPHQL]

172 views Asked by At

So, I'm fairly new to programming and I am trying to only display certain objects from a api response array. Besides that, I am using JSReport and Handlebars. Is there a way to filter out the ones with a special value?

Here's an example code:

    {
  "data": {
    "books": {
      "author": {
        "name": "Book Bookinson",
        "books": [
          {
            "name": "book 1 ",
            "stars": "3"
          },
          {
            "address1": "book 2 ",
            "phone1": "1"
          },
          {
            "name": "book 3 ",
            "stars": "3"
          },
          {
            "address1": "book 4 ",
            "phone1": "3"
          },
        ]
      },
    }
  }

So in the code above, I want to filter out so I only get the object with the "stars": "1", and skip the rest. Is there a clean, easy way to do this that I am yet not aware of? I am aware that I can use the object then index through them, but I get a long list of objects that could really need a filter.

Please go easy on me, freshie here!

1

There are 1 answers

1
KcH On

Not efficient way to do as below but tried my luck using filter and deep cloning object to not alter the main :

 let bookData = {
  "data": {
    "books": {
      "author": {
        "name": "Book Bookinson",
        "books": [
          {
            "name": "book 1 ",
            "stars": "1"
          },
          {
            "address1": "book 2 ",
            "phone1": "1"
          },
          {
            "name": "book 3 ",
            "stars": "3"
          },
          {
            "address1": "book 4 ",
            "phone1": "3"
          },
        ]
      },
    },
  },
  }
  
  let oneStar = JSON.parse(JSON.stringify(bookData)); // deep clone 
  oneStar.data.books.author.books =  oneStar.data.books.author.books.filter(book=>typeof book.stars!=="undefined" && parseInt(book.stars)===1); // filter if book has property stars and equals 1

  /* console.log(bookData) */
  console.log(oneStar);