-1

how can I filter this JSON by the array of areas, within that array? I need to display in my html only the items that have a certain area. In the case below, I must display only the area_one

[
   {
      "ID":789,
      "title":"Title Page",
      "image_desktop":"image21.jpg",
      "image_mobile":"image234.jpg",
      "link":"#",
      "areas":[
         "area_one"
      ]
   },
   {
      "ID":789,
      "title":"Title Page three",
      "image_desktop":"image21.jpg",
      "image_mobile":"image234.jpg",
      "link":"#",
      "areas":[
         "area_one"
      ]
   },
   {
      "ID":765,
      "title":"Title Page 2",
      "image_desktop":"image231.jpg",
      "image_mobile":"image421.jpg",
      "link":"#\/link",
      "areas":[
         "area_two"
      ]
   }
]
3
  • 2
    Array.prototype.filter Commented Apr 20, 2020 at 23:34
  • 1
    + Array.prototype.includes() Commented Apr 20, 2020 at 23:34
  • Of note, you never "filter JSON". You filter an array and JSON is just one of the ways to represent it. Commented Apr 20, 2020 at 23:36

1 Answer 1

1

You can use .filter() for outer array and .some() for the inner one:

let input = [
   {
      "ID":789,
      "title":"Title Page",
      "image_desktop":"image21.jpg",
      "image_mobile":"image234.jpg",
      "link":"#",
      "areas":[
         "area_one"
      ]
   },
   {
      "ID":789,
      "title":"Title Page three",
      "image_desktop":"image21.jpg",
      "image_mobile":"image234.jpg",
      "link":"#",
      "areas":[
         "area_one"
      ]
   },
   {
      "ID":765,
      "title":"Title Page 2",
      "image_desktop":"image231.jpg",
      "image_mobile":"image421.jpg",
      "link":"#\/link",
      "areas":[
         "area_two"
      ]
   }
];

let result = input.filter(x => x.areas.some(area => area === "area_one"));
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.