I am trying to generate nested object from nested array using javascript. But so far not able to succeed.
Below is array example.
let arr = [
'25',
'25_29',
'25_28',
'25_28_35',
'25_28_35_36',
'20',
'20_27',
'20_26',
'18',
'18_48',
'59',
'34'
];
Below is object example.
let Obj = {
25: {
key: 25,
child: {
29: {
key: 29, child: {}
},
28: {
key: 28,
child: {
key: 35,
child: {
key: 36,
child: {}
}
}
}
}
},
20: {
key: 20,
child: {
27: {
key: 27,
child: {}
},
26: {
key: 26,
child: {}
}
}
}
}
Is there any possibility of doing same?
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
-
1I'm sure it's possible, though your input array is invalid, so you'll have to clarify if you want help.junvar– junvar2019年11月01日 14:01:36 +00:00Commented Nov 1, 2019 at 14:01
-
@junvar Array has been updated.Mitesh Vanatwala– Mitesh Vanatwala2019年11月01日 14:06:12 +00:00Commented Nov 1, 2019 at 14:06
2 Answers 2
You could split the path and reduce the keys.
var array = ['25', '25_29', '25_28', '25_28_35', '25_28_35_36', '20', '20_27', '20_26', '18', '18_48', '59', '34'],
result = array.reduce((r, s) => {
s.split('_').reduce((o, key) => (o[key] = o[key] || { key, child: {} }).child, r);
return r;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
answered Nov 1, 2019 at 14:36
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
let arr = ['25', '25_29', '25_28', '25_28_35', '25_28_35_36', '20', '20_27', '20_26', '18', '18_48', '59', '34'];
let obj = arr.reduce((obj, v) => {
let keys = v.split('_');
let o = obj;
keys.forEach(key => {
o[key] = o[key] || {key, child: {}};
o = o[key].child;
});
return obj;
}, {});
console.log(obj);
answered Nov 1, 2019 at 14:32
junvar
11.7k2 gold badges35 silver badges52 bronze badges
Comments
lang-js