Skip to content

Instantly share code, notes, and snippets.

@mkhizeryounas
Last active May 27, 2018 20:17
Show Gist options
  • Save mkhizeryounas/0954b5b1da64668e0b70693edfc7524f to your computer and use it in GitHub Desktop.
Save mkhizeryounas/0954b5b1da64668e0b70693edfc7524f to your computer and use it in GitHub Desktop.
JsonHelper - convert a json to array with values and props i.e. {value: "ghi", prop: ".money.some.arr[2]", key: "2", name: "2", context: "context.money.some.arr[2]"} & dynamic key access by string selecter
/**
-- HOW TO USE --
let data = {
user: "Khizer",
company: "Shopdesk",
showName: "Eid",
money: {
amount: 1000,
currency : "PKR",
some: {
more: 'Khizer',
arr: [
"abc",
"def",
"ghi"
]
}
},
status: true,
messgae: "Call successfull"
}
let tmp = JsonHelper;
console.log(tmp.toArray(data)); // generate for selecter
console.log(tmp.byString(data, ".money.some.arr[2]")) // access by string
*/
class JsonHelper {
constructor () {
this._result = Array();
}
camelCaseToWords(str){
if(!isNaN(str)) return str;
return str.match(/^[a-z]+|[A-Z][a-z]*/g).map(function(x){
return x[0].toUpperCase() + x.substr(1).toLowerCase();
}).join(' ');
};
toArr(obj, p="") {
const result = [];
for (const prop in obj) {
const value = obj[prop];
// let propD = "['"+prop+"']";
let propD = prop;
if(!isNaN(prop)) { // is number
propD = "[" + parseInt(prop) + "]";
}
else {
propD = "."+prop;
}
let tmp = p=="" ? propD : p + propD ;
if (typeof value === 'object') {
result.push(this.toArr(value, tmp)); // <- recursive call
}
else {
result.push({
value,
prop: tmp,
key: prop,
name: this.camelCaseToWords(prop)
});
}
}
return result;
}
extractElements (obj) {
obj.forEach(e=>{
if(Array.isArray(e)) {
this._result = this.extractElements(e);
}
else {
this._result.push(e);
}
})
return this._result;
}
toArray(d) {
this._result = Array();
let arrayTmp = this.extractElements(this.toArr(d));
arrayTmp.forEach(e=>{
e.context = "context"+e.prop;
})
return arrayTmp;
}
byString (o, s) { // obj , prop
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment