thichxai
thichxai

Reputation: 1147

Marklogic Javascript for loop

I have multiple json format. How can I loop throught json files to display developers' name. Thanks

example:

doc1.json

{
 "script": "collectionlib.sjs"
 "version": "1.0.1"
 "Developers":"Melvin Mckee"
}

doc2.json

{
 "script": "TechReports.sjs"
 "version": "1.1.5"
 "Developers":"Brenton York"
}

I can do for single json file.

 'use strict';
  var doc = cts.doc("/doc1.json")
  var node = xdmp.toJSON(doc)
  node.root.Developers

//Return result: "Melvin Mckee"

but not sure how to construct For..Loop to get result back developers name are "Melvin Mckee" and "Brenton York"

var items = cts.uris(null,
                    null,
                    cts.collectionQuery("scripts-collection")
           ) 

for (var i = 0; i < items.length;i++){
     var doc = cts.doc(items[i]);
     var node = xdmp.toJSON(doc); 
     node.root.developers
  }

I got result NULL on Qconsole.

Upvotes: 1

Views: 190

Answers (1)

Dave Cassel
Dave Cassel

Reputation: 8422

Part of the problem is the node.root.developers has a lower-case 'd', while the data you provided has an upper-case 'D'. That may have been a typo.

MarkLogic returns the value of the last expression, but the for loop doesn't return a value. What you want to do is declare an array variable before the loop, add to it during the loop, then return that variable.

Try this:

let uris = 
  cts.uris(
    null,
    null,
    cts.collectionQuery("scripts-collection")
  ) 

let devs = [];

for (let uri of uris) {
  let doc = cts.doc(uri);
  let node = xdmp.toJSON(doc);
  devs.push(node.root.Developers);
}

devs

Upvotes: 3

Related Questions