Say you have some object:
var data = [
{
type:"Person",
name: "Suzanne",
pets:[
{
type:"Cat",
name:"Charles"
}
],
children:[
{
type:"Person",
name:"Chelsey",
pets:[
{
type:"Cat",
name:"Charlotte"
},{
type:"Cat",
name:"Vicky"
}
]
},{
type:"Person",
name:"Drake",
pets:[
{
type:"Dog", name:"Ploddy"
}
]
}
]
},{
type:"Person",
name: "Arun",
pets:[
{
type:"Cat",
name:"Jackson"
}
]
}
]
Say that we want to find all People who have Cats as pets. Because of the nested structure of our data it becomes slightly difficult, as children also have pets.
This is where Object.query comes in:
var results = data.query(function(obj){
return obj.type=="Person" && obj.pets!=undefined && obj.pets.filter((pet)=>pet.type=="Cat").length!=0
})
This will return the following data:
{
"root.0":{"type":"Person","name":"Suzanne","pets":[{"type":"Cat","name":"Charles"}],"children":[{"type":"Person","name":"Chelsey","pets":[{"type":"Cat","name":"Charlotte"},{"type":"Cat","name":"Vicky"}]},{"type":"Person","name":"Drake","pets":[{"type":"Dog","name":"Ploddy"}]}]},
"root.0.children.0":{"type":"Person","name":"Chelsey","pets":[{"type":"Cat","name":"Charlotte"},{"type":"Cat","name":"Vicky"}]},
"root.1":{"type":"Person","name":"Arun","pets":[{"type":"Cat","name":"Jackson"}]}
}
Such that:
Object.values(results).map(function(person){return person.name}) //=>["Suzanne","Chelsey","Arun"]
Ultimately, query provides a quick and easy way to search objects.
It also works for recursive object structures!
You should be able to check for recursive structure with the following condition:
var results = document.body.query((obj)=>obj instanceof Object && obj[Object.seen_symbol])
However this currently doesn't work?