Search code examples
javascriptjavascript-objects

Filter Object based on whether objects contain detail property


I have an object thats returning from an API.

I want to process it easily in Javascript and return only the tests that have a "Grade" property.

The structure of the object looks like this:

{
  "ScoreCard": {
    "tests": {
      "test1": {
        "id": 100,
        "score": 0,
        "details": {
          "type": "table"
        }
      },
      "test2": {
        "id": 200,
        "score": 1,
        "details": {
          "type": "Grade"
        }
      },
//moretests
}

Is there an easy way to do this with something like Filter?

I know I can get the keys from the Object using

var keys = object.keys(response)

and if I iterate through that I can create a result set- but it seems very cumbersome. I am sure there is a simpler solution - that I am not considering.


Solution

  • Use Object.entries method to get each key-value pair and then use Array#reduce method to iterate over the array and generate a combined object.

    const data = {
      "ScoreCard": {
        "tests": {
          "test1": {
            "id": 100,
            "score": 0,
            "details": {
              "type": "table"
            }
          },
          "test2": {
            "id": 200,
            "score": 1,
            "details": {
              "type": "Grade"
            }
          },
          //moretests
        }
      }
    }
    let o;
    
    let res = Object.entries(data.ScoreCard.tests).reduce((obj,  [k, o]) => {
      if (o.details.type === "Grade") obj[k] = o;
      return obj
    }, {})
    
    console.log(res)

    One-liner solution:

    let res = Object.entries(data.ScoreCard.tests).reduce((obj, [k, o]) => (o.details.type  === "Grade" && obj[k] = o[k], obj), {})