Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 7bcdad3

Browse files
authoredFeb 5, 2018
json-csv for simple json, v1 implementation
1 parent 1bb540c commit 7bcdad3

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
 

‎json-csv.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
const getSchema = data => {
2+
const schema = [];
3+
4+
if (Array.isArray(data)) {
5+
data.forEach(row => {
6+
Object.keys(row).forEach(key => {
7+
if (schema.indexOf(key) === -1) {
8+
schema.push(key);
9+
}
10+
});
11+
});
12+
}
13+
14+
return schema;
15+
};
16+
17+
const generateResultSet = (data, schema) => {
18+
const resultSet = [];
19+
20+
data.forEach(row => {
21+
const resultRow = [];
22+
23+
schema.forEach(key => {
24+
resultRow.push(row[key] || "");
25+
});
26+
27+
resultSet.push(resultRow);
28+
});
29+
30+
return resultSet;
31+
};
32+
33+
// how to deal with nested structures
34+
const data = [
35+
{
36+
code: 1234,
37+
name: "abcd"
38+
},
39+
{
40+
code: 5678,
41+
name: "pqrs"
42+
}
43+
];
44+
45+
const schema = getSchema(data);
46+
const resultSet = generateResultSet(data, schema);
47+
console.log(resultSet);

0 commit comments

Comments
 (0)
Please sign in to comment.