@imatyushkin/deep-query
v0.1.1
Published
Easy data chains for JavaScript
Downloads
3
Readme
At a Glance
DeepQuery.js
solves the problem of null element inside of long object chain.
How to Get Started
Type in Terminal:
npm install --save @imatyushkin/deep-query
or, if you prefer yarn
over npm
, type:
yarn add @imatyushkin/deep-query
Usage
Simple Query
Let's assume we have some JavaScript object with complicated structure of nested objects:
var obj = {
a: {
b: [
{ val: [1,2,3] },
{ val: [4,5,6] },
{ val: null },
]
}
};
Now, we want to obtain a value located very deep in the tree:
var regularQuery = obj.a.b[2].val[0] // CRASH 😡
We'll get crash because the val
is null
, which might be an unexpected case. To avoid this, we could implement a more complicated logic based on data structure:
var safeQuery = (() => {
var intermediateResult = obj.a.b[2];
return intermediateResult.val ? intermediateResult.val[0] : null;
})();
With DeepQuery.js
it works significantly easier:
import "@imatyushkin/deep-query"
var query = obj.__("a.b.2.val.0") // No crash, just null will be returned 🙂
var anotherQuery = obj.__("a.b.1.val.0") // 4
Filter
Here's example of query with data filter:
var data = {
users: [
{
name: "John",
points: [10,9,5]
},
{
name: "Donald",
points: [8, 4, 2]
}
]
}
var pointsOfJohn = data.__("users.name:John.0.points") // [10, 9, 5]
Multiline Query
For convenience, you may use a multiline expression:
// Instead of
var pointsOfJohn = data.__("users.name:John.0.points")
// use
var pointsOfJohn = data.__(`
users
.name:John.0
.points
`)
License
DeepQuery.js
is available under the Apache 2.0 license. See the LICENSE file for more info.