Search code examples
javascriptnode.jsjsonobject

Javascript: Filter a JSON conditionally based on the value of a key?


After retrieving a JSON such as this:

"JSON": [
{
  "mySchool": "college",
  "myHome": "apartment",
  "myFavoriteSport": "soccer"
},
{
  "mySchool": "highschool",
  "myHome": "house",
  "myFavoriteSport": "hockey"
},
{
  "mySchool": "college",
  "myHome": "box",
  "myFavoriteSport": "soccer"
},
{
  "mySchool": "elementary",
  "myHome": "tent",
  "myFavoriteSport": "soccer"
}
]

How could I filter it conditionally so that... if soccer is the value of myFavoriteSport key, then return an array of all objects containing the myFavoriteSport: soccer pair? I'm sure I'll end up pushingthe object into the array at the end, but I don't quite know how to single it out so that I can assign it to a variable.

I'm sure it will involve some type of loop, but this is my first time working with JSON and objects of this type so I'm a little unsure of how to approach it.


Solution

  • If you want to filter, then use .filter - just check if the myFavoriteSport property is soccer:

    const input = {
      "JSON": [
        {
          "mySchool": "college",
          "myHome": "apartment",
          "myFavoriteSport": "soccer"
        },
        {
          "mySchool": "highschool",
          "myHome": "house",
          "myFavoriteSport": "hockey"
        },
        {
          "mySchool": "college",
          "myHome": "box",
          "myFavoriteSport": "soccer"
        },
        {
          "mySchool": "elementary",
          "myHome": "tent",
          "myFavoriteSport": "soccer"
        }
      ]
    };
    console.log(
      input.JSON.filter(({ myFavoriteSport }) => myFavoriteSport === 'soccer')
    );

    Also note that JSON is a way of representing an object in string format. (for example,

    const myJSON = '[{"foo":"bar"},{"baz":"buzz"}]';
    

    ). If you have the actual object/array, then it's not in JSON format - it's just a plain object. Better to name the key something like arr or personArr or something like that. There's no such thing as a "JSON Object"