-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtoCSVArray.js
More file actions
46 lines (42 loc) · 1.21 KB
/
toCSVArray.js
File metadata and controls
46 lines (42 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const flatten = require("flat");
const flattenData = (dataArr) =>
dataArr.map((item) =>
typeof item === "string" ? item : flatten(item, { safe: true })
);
const toCSVArray = (data, duplicateRows = true) => {
return flattenData(data).reduce((acc, item) => {
let newItem = {};
let toConcat = [];
for (const key in item) {
const itemValue = item[key];
if (!(typeof itemValue === "object" && Array.isArray(itemValue))) {
newItem[key] = item[key];
} else if (
Array.isArray(itemValue) &&
itemValue.every((item) => typeof item === "string")
) {
toConcat = toConcat.concat(
itemValue.map((item) => {
return { [`${key}`]: item };
})
);
} else {
toConcat = toConcat.concat(toCSVArray(itemValue));
}
}
if (duplicateRows) {
if (toConcat.length) {
toConcat.forEach((concatItem) =>
acc.push({ ...newItem, ...concatItem })
);
} else {
acc.push(newItem);
}
return acc;
}
const [firstItem = {}, restItems = []] = toConcat;
acc.push({ ...newItem, ...firstItem });
return acc.concat(restItems);
}, []);
};
module.exports = toCSVArray;