5

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.

Austin Burke
  • 148
  • 2
  • 10

2 Answers2

5

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"

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • So I gave it a try and received a lot of errors. `(node:62645) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'filter' of undefined at Object.module.exports.handler` is one of them – Austin Burke Oct 13 '18 at 00:36
  • This is the other `at process._tickCallback (internal/process/next_tick.js:189:7) (node:62645) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catchblock, or by rejecting a promise which was not handled with .catch().` – Austin Burke Oct 13 '18 at 00:37
  • You didn't specify the name of the object variable your `"JSON"` property is in, so it's impossible to say from here exactly what the code should be - whatever the variable name is, substitute that into the place where `input` is in the code in my answer. eg `myObj.JSON.filter` or something like that. – CertainPerformance Oct 13 '18 at 00:38
  • I thought I did specify it like this `const data = JSON.parse(response);` and then using the code in your answer, `console.log( data.JSON.filter(({ myFavoriteSport }) => myFavoriteSport === 'Soccer') );` – Austin Burke Oct 13 '18 at 00:40
  • I console.logged `data` and I know it logs the JSON properly – Austin Burke Oct 13 '18 at 00:41
  • Almost, that should work, if `response` is a JSON string containing the object in your question, except that your `'Soccer'` should be `'soccer'` (lower case), see https://jsfiddle.net/qs1mpfy0/ – CertainPerformance Oct 13 '18 at 00:41
  • It works just fine for me, it returns an array containing the three objects with `soccer`. Sounds like a problem with your browser? Were there any errors? Because you used `JSON.parse` to turn the string into an object beforehand, that shouldn't be a problem – CertainPerformance Oct 13 '18 at 01:12
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/181790/discussion-between-austin-burke-and-certainperformance). – Austin Burke Oct 13 '18 at 01:16
0

It's pretty easy to achieve with filter() array method, there is a one line solution: you can specify a condition inside a callback function, and finally you will get a new array of items, which fits this condition.

const 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"
  }
];

const result = JSON.filter(item => item.myFavoriteSport === 'soccer');
console.log(result);

You can also achieve such result using many other array iteration methods, but filter perfectly fits your needs.

P.S.
  • 15,970
  • 14
  • 62
  • 86