JSFiddle - React, Tailwind, and code Playground
by habla
JavaScript
function Query(obj) {
this.object = obj;
}
function query(obj) {
return new Query(obj);
}
Query.prototype.get = function(key) {
if (this.object)
{
return new Query(this.object[key]);
}
return new Query(null);
}
Query.prototype.getEach = function(key) {
if (this.object && this.object.constructor === Array)
{
return new Query(
this.object.map(function (item) { return item[key]; })
.filter(function (item) { return !!item; })
);
}
return new Query(null);
}
Query.prototype.at = function(idx) {
if (this.object)
{
return new Query(this.object[Number(idx)]);
}
return new Query(null);
}
Query.prototype.first = function() {
return this.at(0);
}
Query.prototype.result = function() {
return this.object ? this.object : null;
}
jsonex = { "A" : 10, "B" : [1,2,{"foo": "baz"}, {"foo": "bar"}]};
var result;
result = query(Query.prototype.result).get("A").result();
console.log(JSON.stringify(result));
result = query(jsonex).get("A").result();
console.log(JSON.stringify(result));
result= query([1,2,{"a":10}]).get("a").result();
console.log(JSON.stringify(result));
result= query(jsonex).get("C").result();
console.log(JSON.stringify(result));
result = query(jsonex).get("B").result();
console.log(JSON.stringify(result));
result = query(jsonex).get("B").getEach("foo").result();
console.log(JSON.stringify(result));
result = query(jsonex).at(4).result();
console.log(JSON.stringify(result));
result = query([5,4,3,2,1,0]).at(4).result();
console.log(JSON.stringify(result));
result = query([5,4,3,2,{a:"b"},0]).at(4).get('a').result();
console.log(JSON.stringify(result));