1

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?

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
nxtlvl
  • 21
  • 3

1 Answers1

0

You can make an array of the two arrays you are interested in, then flatten the resulting array of array with the flatten operator [].

Which gives you the query:

[domains, subdomains][]

And so your JavaScript search ends up being:

const result = JMESPath.search(arrayItem, '[domains, subdomains][]');

This would result in the expected array:

[
  "somedomain.com",
  "otherdomain.com",
  "mail",
  "docs"
]
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
  • This will do the trick for the application of this program, we will simply have to write better JMESPath queries. Thanks! But for future reference, I'm also interested in learning if it is in fact possible to perform multiple seperate search parameters in a single string, or if we simply have to make the single search string work as intended. – nxtlvl Dec 23 '22 at 15:17
  • You are doing no parameter search at all here, merely a rearrangement of the JSON structure. The best would be that you open a new question with a made-up example input and desired output of what you mean by _perform multiple seperate search parameters in a single string_. – β.εηοιτ.βε Dec 23 '22 at 20:27