In addition, let me refactor this a bit:
function getWords(str = '') {
return str.trim().split(' ')
}
function createSubobjects(str = '') {
if (str.length > 1) {
return {
[str[0]]: createSubobjects(str.slice(1))
}
}
return str
}
const data = ["avinash", "supte"]
const index = data.reduce((node, entry) => {
if (entry) {
getWords(entry)
.forEach(word => {
Object.assign(node, createSubobjects(word))
})
}
return node
}, {})
console.log(index)
This is a bit shorter and more readable.