Skip to content

Instantly share code, notes, and snippets.

@gbrian
Created November 28, 2017 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbrian/1c1aedd19ca7d23836d71b6db375d757 to your computer and use it in GitHub Desktop.
Save gbrian/1c1aedd19ca7d23836d71b6db375d757 to your computer and use it in GitHub Desktop.
function cartesian(arr) {
return arr.reduce((a, b) =>
a.map(x => b.map(y => x.concat(y)))
.reduce((a, b) => a.concat(b), []), [[]]);
}
function parse(f){
var re = /\[([0-9a-zA-Z,]+[^\]]+)\]/gm;
var m = null;
var res = [];
var lastIndex = 0;
while(m = re.exec(f)){
res.push([f.substring(lastIndex, m.index)]);
res.push(m[1].split(",").map(i => "."+i));
lastIndex = m.index + m[0].length;
}
return cartesian(res).map(r => r.join(""));
}
/**
* This makes part of a JSON2CSV engine
* The idea is to simplify the syntax to select fields from complex objects
*
* Given the document
*/
var o = { a:{
b:['val1'],
c:[{
d:1,
e: 'val2',
f: 2.3
}],
c1:[{
d:1,
e: 'val2',
f: 2.3
}]
}
}
parse("a[c,c1][0][e,f]").map(k => [k, eval("o." + k)])
/* OUTPUT
(4) [Array(2), Array(2), Array(2), Array(2)]
0:(2) ["a.c[0].e", "val2"]
1:(2) ["a.c[0].f", 2.3]
2:(2) ["a.c1[0].e", "val2"]
3:(2) ["a.c1[0].f", 2.3]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment