Franchy
Franchy

Reputation: 152

Filter a multidimensional json array by specific element with jquery

I have the following json array:

{"0":  
   {"ChkSystem":
      {"id":"847",
       "item":"1",
       "fase":"#FE99CC",
       "description":"some info.",
       "image_path":"",
       "pm_id":"461",
       "main_systems_id":"1"
      }
   },
 "1":
   {"ChkSystem":
      {"id":"846",
       "item":"1",
       "fase":"#FE99CC",
       "description":"some data",
       "image_path":"",
       "pm_id":"461",
       "main_systems_id":"2"
      }
   },
"2":
  {"ChkSystem":
     {"id":"856",
      "item":"2",
      "fase":"#FE99CC",
      "description":"some data.",
      "image_path":"",
      "pm_id":"461",
      "main_systems_id":"2"
     }
  }
}  

How can I filter it by "main_systems_id" with jquery?
The problem is the key is variable ("0", "1" and so on) and in other posts that I had read that key is always the same.

Thanks in advance for your answers.

Upvotes: 1

Views: 2637

Answers (2)

Nijikokun
Nijikokun

Reputation: 1524

I think a tool like lodash or underscore is more suited for something of this nature.

However should you really want to do it with jQuery:

function filterByMainSystemsId (object, value) {

  // The real meat of the solution, you can use this directly if you want.
  return $.map(object, function (item, key) { 

      // this is where the check is done
      if (item.ChkSystem.main_systems_id === value) {

        // if you want the index or property "0", "1", "2"... etc.
        // item._index = key;

        return item; 
      }
    });
  };
}

var object = /* ... your object goes here ... */;
var array = filterByMainSystemsId(object, "2") // [ { ... }, { ... } ]

I agree however, this should be an array and not an object, but things like elasticsearch and other tools make this hard and I can understand that.

Upvotes: 1

Daniel
Daniel

Reputation: 3514

This is not an array, but an object, containing sub objects. This would be the code for a json array:

[
{"ChkSystem":
      {"id":"847",
       "item":"1",
       "fase":"#FE99CC",
       "description":"some info.",
       "image_path":"",
       "pm_id":"461",
       "main_systems_id":"1"
      }
   },
   {"ChkSystem":
      {"id":"846",
       "item":"1",
       "fase":"#FE99CC",
       "description":"some data",
       "image_path":"",
       "pm_id":"461",
       "main_systems_id":"2"
      }
   },
  {"ChkSystem":
     {"id":"856",
      "item":"2",
      "fase":"#FE99CC",
      "description":"some data.",
      "image_path":"",
      "pm_id":"461",
      "main_systems_id":"2"
     }
  }
]

but you can also loop through json objects (key value pairs) and furthermore filter them. See StackOverflow: loop and get key/value pair for JSON array using jQuery

Upvotes: 0

Related Questions