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?

New contributor
Mitesh Vanatwala is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • 1
    I'm sure it's possible, though your input array is invalid, so you'll have to clarify if you want help. – junvar 2 days ago
  • @junvar Array has been updated. – Mitesh Vanatwala 2 days ago
1

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; }

1

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);

Your Answer

Mitesh Vanatwala is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.