I want to be able to perform multiple searches inside a JSON using JMESPath with JavaScript, so I don't have to iterate over the large object for each JMESPath search string I need to perform.
I have this example object (let's call it arrayItem):
{
"domains": ["somedomain.com", "otherdomain.com"],
"subdomains": ["mail", "docs"]
}
I'm trying to query both these fields and collect the data in a new array using JavaScript, like so:
const result = JMESPath.search(arrayItem, ["domains[]", "subdomains[]"])
Where one JMESPath search is "domains[]" and the other is "subdomains[]".
But this does not work. I get null
as a result. I have one solution, which is to perform a forEach()
function for each of the items, but I don't think this is the optimal way as I have to iterate over a huge dataset x number of times instead of a single search.
This "hacky" solution provides the desired output when pushing each item to an array:
let whatIwantArray = []
jmesSearches = ["domains[]", "subdomains[]"]
jmesSearches.forEach((jmesSearch) => {
const result = JMESPath.search(arrayItem, jmesSearch)
result.forEach((domain) => {
whatIWantArray.push(domain)
})
})
console.log(whatIwantAraay)
The output with the loop, which is also the output expected from the JEMSPath query:
["somedomain.com", "otherdomain.com", "mail", "docs"]
How can this be done?