Jsqry - a library for querying JS objects and arrays

    I present to your attention a small js-library Jsqry .
    The easiest way to illustrate its purpose is as follows.


    Before:


    var name;
    for (var i = 0; i < users.length; i++) {
        if (users[i].id == 123) {
            name = users[i].name;
            break;
        }
    }

    After:


    var name = one(users, '[_.id==?].name', 123);

    The library allows you to extract information from objects / arrays in one line, using a simple query language, instead of writing loops (sometimes nested).


    In fact, it implements only two functions:


    • query - to return a list of results and
    • one - to return the first result found.

    The list of features includes:


    1. Filtering
    2. Transformation
    3. Python style indexes / slices

    The library appeared spontaneously in one project, built on the now fashionable single-page application approach . We load one large JSON, parts of which are then used to render different views of the site on the client. And now for tearing out these very parts, I wanted a more convenient way. Then, however, the library was in demand in other cases.


    I will explain a little on the functionality. The request in the general case may take the form


    field1.field2[ condition or index or slice ].field3{ transformation }.field4

    Here:


    • field1.field2.field3 ... - regular access to the fields of objects, as in js
    • [condition] - filtering
    • [index] - access by index, same as in js
    • [from: to: step] - slices in the style of Python
    • {transformation} - transformation of objects

    On condition and transformation it is worth stopping in more detail.
    In fact, everything is very simple. It is enough to understand that each expression inside square / curly brackets is replaced with a function during execution according to this principle:


    condition_or_transformation ⟶ function (_, i) {return condition_or_transformation }


    (here _ is the value of the transmitted element, i is its index).


    Example:


    query([1,2,3,4,5],'[_>2]{_+10}') // [13, 14, 15]

    Request parameterization is also supported:


    query([1,2,3,4,5],'[_>?]{_+?}', 2, 10) // [13, 14, 15] 

    By combining these features, you can build very complex and flexible queries. More usage examples can be found here .


    From interesting implementation - AST query tree is cached, which gives the library speed.


    Of course, my library is not unique in its kind. It is worth giving a "small" list of analogues:



    Why another library? In fact, it does not support the entire possible range of request types, but only what was needed in our project in most cases. Due to this, simplicity and speed. Also, an extremely simple API inspired by the jQuery approach.


    I will be glad to hear criticism and suggestions for improvement.


    Also popular now: