I have been racking my head to solve this. Assuming we have the below CSV
const csv=[ "col1,col2,col3,col4,col5,col6", "frequency,Weekly,haha,U45,A,WEEKLY", "frequency,Every two weeks,def,hel,B,BI-WEEKLY", "Time,Monthly,ghi,Tar,C,MONTHLY", "Time,Every two months,oiu,60T,D,BI-MONTHLY", "type,Quarterly,ppp,Q12,E,QUARTERLY", "type,Half yearly,qwf,Y34,F,SEMI-ANNUALLY"]
what i am trying to do is create the nested json, which is not working in addition to that to get the below in a new json file, named with the value of col1. meaning grouping all rows with a common col1 in a single file like below. if col3, col 4 are the same & col5 & col6 are different the nest should be as below. drop col2.
{ "haha": { "U45": { "A": "Weekly" "B": "Semi-annually" } } }
what i have done so far is this.
const attrs = csv.splice(0,1); function nested (obj, path, value) { let lastKeyIndex=path.length-1; lastKeyIndex.map(i => { let key = path[i]; if (!(key in obj)) { obj[key]={} } obj=obj[key] }) obj[path[lastKeyIndex]]=value; } csv.map(line => { let [col1,col2,col3,col4,col5,col6] = line.split(',') let obj={} nested (obj, [col3, col4, col5], col6) return obj })
your help is greatly appreciated.
Advertisement
Answer
You will have to use the node fs plugin to save the different files. I’ve marked the lines that you should uncomment in the node environment with // node only
.
What I’ve done is loop through col3
– col6
, check if the property exists in the parent object, if not create a new object, and then use that to check for the children. If you are on the last property, instead of creating a new object, use col6
.
// const fs = require("fs"); // node only let csv = [ "col1,col2,col3,col4,col5,col6", "frequency,Weekly,haha,U45,A,WEEKLY", "frequency,Every two weeks,def,hel,B,BI-WEEKLY", "Time,Monthly,ghi,Tar,C,MONTHLY", "Time,Every two months,oiu,60T,D,BI-MONTHLY", "type,Quarterly,ppp,Q12,E,QUARTERLY", "type,Half yearly,qwf,Y34,F,SEMI-ANNUALLY" ]; csv.splice(0, 1); function addProperty(root, pathList) { var lastValue = pathList.splice(pathList.length - 1, 1)[0]; pathList.forEach(function (path, index) { var obj = root[path]; if (!obj) { obj = (index === pathList.length - 1) ? lastValue : {}; root[path] = obj; } root = obj; }); } function jsonText(obj) { return JSON.stringify(obj, (key, value) => value, 4); } var files = csv.reduce(function (result, line) { var [fileName, , ...pathList] = line.split(","); var fileInfo = result[fileName]; if (!fileInfo) { fileInfo = {}; result[fileName] = fileInfo; } addProperty(fileInfo, pathList); return result; }, {}); console.log(jsonText(files)); // for (var path in files) fs.writeFileSync(path + ".json", jsonText(files[path])); // node only