For exemple I have arr
var arr = [
{
nID: 1,
sLogin: 'user1',
sParent: ''
},
{
nID: 2,
sLogin: 'user2',
sParent: 'user1'
},{
nID: 3,
sLogin: 'user3',
sParent: ''
},
]
And I need to make an Obj that's gonna look like this
{
"user1": {
nID: 1,
sLogin: 'user1',
sParent: '',
oChild: {
"user2": {
nID: 2,
sLogin: 'user2',
sParent: 'user1'
}
}
},
"user3": {
nID: 3,
sLogin: 'user3',
sParent: ''}
}
We need to track "sLogin" and "sParent" and if it matches we should set into "oChild" to the parent's object and remove from the main
First I created a mapping object for users that have a parent so that I can easily pick the child from the mapping object. It will look like this
{
user2: {
nID: 2,
sLogin: "user2",
sParent: "user1"
}
}
After that i did a reduce on the original array and picked from the mapping when sParentis not an empty string
var arr = [{nID: 1,sLogin: 'user1',sParent: ''},{nID: 2,sLogin: 'user2',sParent: 'user1'},{nID: 3,sLogin: 'user3',sParent: ''},]
const mapping = {}
arr.forEach(el => {if(el.sParent !== '') mapping[el.sLogin]=el})
const res = arr.reduce((acc,curr)=>{
const {nID,sLogin,sParent} = curr
if(sParent===''){
acc[sLogin]=curr
}
else{
acc[sParent]['oChild'] = {}
acc[sParent]['oChild'][sLogin] = mapping[sLogin]
}
return acc;
},{})
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }