Filtering through JSON sub-objects in JavaScript

I am trying to filter through "carObj" below, since the user selects "filters" from the list on the page and displays only the "relevant" sub-objects.

Currently, when the user selects a "filter", it is added to "filterObj", and then I scroll through the "carObj" using like 8 $ .each operators to pull out all the relevant sub-objects. I compare with values ​​and scan many times to do this.

For example, assuming the example below, only the 3rd sub-object in "carObj" will be "returned" with all its values. Because this means that I set the attribute "TRUE" for all matches and "FALSE" for all that do not.

Then on the webpage, I look through all the TRUE-valued sub-objects in "carObj" and display their information / values ​​in the table.

I am not sure if this is the most efficient way to do this.

 /* Object filled as user selects "filters" */
 filterObj ={
    "Seats": {},
    "color": {
        "Orange": "Orange",
         "Red": "Red"
        },
    "Transmission": {
        "Manual": "Manual"
    },
    "Make": {
        "Ford": "Ford"
    },
    "Model": {},
    "Status": {
        "New": "New"
        }

}

/* Main object that contains all cars */
carObj = {
  "cars": [
   {
      "seats":"6",
      "color":"Red",
      "transmission":"Automatic",
      "make":"Ford",
      "model":"Windstar",
      "status":"New",
   },
   {
      "seats":"4",
      "color":"Black",
      "transmission":"Manual",
      "make":"Mazda",
      "model":"CRX",
      "status":"New",
   },
   {
      "seats":"2",
      "color":"Orange",
      "transmission":"Manual",
      "make":"Ford",
      "model":"Galaxy",
      "status":"New",
   }
  ]
}
+4
source share
1 answer

It was complicated. See this script .

Questions:

  • Do not use objects in the filter object. For this, I used simple arrays:

    "color": {
        "Orange": "Orange",
        "Red": "Red"
    },
    

    to

    "color": ["Orange", "Red"],
    

    It will be simpler and more logical;

  • I changed the keys as the first letter in uppercase in all arrays and objects. Another way that the algorithm would have to take care of this, and configure it according to its functionalities. I fixed this to make the script smaller, but if it could work with non-standard key names,

  • carObj, , . .

, , 100%. . /, .

, .

UPDATE:

, . .

, Color ["Orange"], , , Color ["Orange", "Red"], Orange Red. , Color: [], .

+3

Source: https://habr.com/ru/post/1525612/


All Articles