goofballLogic / ld-query

Querying JSON-LD
MIT License
20 stars 6 forks source link

Simplifying processing of array elements #18

Closed gareth-robinson closed 8 years ago

gareth-robinson commented 8 years ago

For the same document in the README.md, how would I go about mapping the entries under favouriteReads to my own document model?

At the moment I would have to do

var favs = doc.query("ex:favouriteReads"); // query for favouriteReads
if ( favs ) {  // check it isn't null
  model = favs.json() // get the array
    .map( x => ldQuery( x ) ) // map each aray entry to a new query object
    .map( x=> ( { // query again to create my own document model
      author: x.query( "so:author @value" ),
      title: x.query( "so:name @value" )
    } ) );
}

Is there a shorter way to do this? I guess one way could be that if you use 'queryAll' against a path ("ex:favouriteReads") that points to an array that you get each entry of the array as a QueryNode? Or might that lead to confusing use cases?

The other option would be wildcards e.g.

model = doc.queryAll("ex:favouriteReads > *") // query for all children of favouriteReads
// since queryAll returns either an empty array or an array of queryNodes
// you can skip the safety check and go directly to mapping
    .map( x=> ( { 
      author: x.query( "so:author @value" ),
      title: x.query( "so:name @value" )
    } ) );

What do you think?

gareth-robinson commented 8 years ago

Nevermind, doc.queryAll("ex:favouriteReads") actually does what I need it too already.