How to access array of objects in Marklogic jsearch mapper function

Viewed 44

I have a JSON document in format below in a collection:

{
 "id":{
  "idValue":[
   {"value1": ["a"],
    "value2":["b"]
   },
   {"value1": ["a"],
    "value2":["c"]
    }
  ]
 }
}

I need to fetch the JSON documents having "value1"=="a" and "value2"=="b" and return only that instance.

I have used jsearch in my code as below

const jsearch = require('/MarkLogic/jsearch.sjs');
var prodct = jsearch.collections(["idCollection"]);
function mapper(result) {
 return {
  value1: result.document.id["idValue"],
  value2: result.document.id["idValue"]
 };
}
var output=
 prodct.documents()
.where(cts.andQuery([cts.jsonPropertyWordQuery("value1","a"),cts.jsonPropertyWordQuery("value2","b")]))
.slice(0,10)
.map(mapper)
.result();
output.results

How to access the array of values in mapper function ?

1 Answers

You could reference the array items by their index. When you want the value of the node, use .valueOf():

function mapper(result) {
 const idValue = result.document.id.idValue[0]
 return {
  value1: idValue.value1[0].valueOf(),
  value2: idValue.value2[0].valueOf()
 };
}
Related