Lucky Agbaroji Lucky Agbaroji - 2 months ago 7
JSON Question

How to query JSON objects

I'm working with a json file that has the following data structure.

{"students":[
{"Name":"Wale", "state":"Lagos", "age":20, "hobby":"dancing"},
{"Name":"Ebere", "state":"Enugu", "age":18, "hobby":"eating"},
{"Name":"Musa", "state":"Kano", "age":24, "hobby":"swimming"}
]}


I'm working with the ionic framework and need to select all students from three variables say...
state, age and hobby. if this was an sql statement it will look something like....

$query = "Select * from students WHERE state = 'Enugu' AND age = '20' AND hobby = 'swimming'".


So my question is; how can I do this in json.

Thanks so much for your anticipated help.

Answer

You could use .filter() to "query" your data set. For the specific case that you described, would be:

let data = {"students":[
    {"Name":"Wale", "state":"Lagos", "age":20, "hobby":"dancing"},
    {"Name":"Ebere", "state":"Enugu", "age":18, "hobby":"eating"},
    {"Name":"Musa", "state":"Kano", "age":24, "hobby":"swimming"}
]};

// ES6!!!
function filterStudents(students, name, age, state){
    return students.filter(student => student.state === state && student.age === age && student.Name === name)
}

console.log(filterStudents(data.students, 'Musa', 24, 'Kano'))

But i would suggest you to go with a library instead of creating your filtering cases manually. See if that lib (i'm the creator) will suit to your case:

https://github.com/DiegoZoracKy/data-query

Comments