1

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
asked Nov 1, 2019 at 13:58
2
  • 1
    I'm sure it's possible, though your input array is invalid, so you'll have to clarify if you want help. Commented Nov 1, 2019 at 14:01
  • @junvar Array has been updated. Commented Nov 1, 2019 at 14:06

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.