const log = console.warn
console.clear()
const dataToTree = data => {
const parent = data.filter(
(value) => value.parent === "undefined" || value.parent == null || value.parent == ""
)
const children = data.filter(
(value) => value.parent !== "undefined" && value.parent != null && value.parent !== ""
)
const translator = (parent, children) => {
parent.forEach((parent) => {
children.forEach((current, index) => {
if (current.parent === parent.name) {
translator([current], children)
Array.isArray(parent.children) ? parent.children.push(current) : (parent.children = [current])
current.parent = parent
}
})
})
}
translator(parent, children)
return parent
}
const processCsv = csv => {
let processedArr = csv.split('\n').filter(item => item !== "")
let keys = processedArr.shift().split(',')
let obj = processedArr.map(item => {
return item.split(',').reduce((tol, cur, i) => {
if (keys[i] === 'parent' && cur === '') {
cur = null
}
return { ...tol, [`${keys[i]}`]: cur }
}, { children: null })
})
return dataToTree(obj)
}
const csv = `
name,age,parent
Bob,30,David
David,60,
Anna,10,Bob
Anna2,10,Bob
`
let result = processCsv(csv)
log(result)
console