Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch path field value from nested objects(Parent- child) using underscore.js

var levels= [
 {
  path: 'RS',
  hasChild :true
 },
    {
     path: 'MO',
     hasChild: true
    },
       {
        path: 'EL',
        hasChild: true   
       },
          {
            path: 'CL',
            hasChild: false
          },
       {
        path: 'EL1',
        hasChild: true   
       },
          {
            path: 'CL1',
            hasChild: false
          },
{
  path: 'RS2',
  hasChild :true
 },
    {
    path: 'MO2',
    hasChild: true
    },
      {
       path: 'EL2',
       hasChild: true   
       },
          {
            path: 'CL2',
            hasChild: false
          },
          {
            path: 'CL3',
            hasChild: false
          },
];

Is it possible to create complete path from the object 'level' using underscore.js? For e.g. -
RS\MO\EL\CL
RS\MO\EL1\CL1
RS2\MO2\EL2\CL2
RS2\MO2\CL3\CL3
In any of the above levels child can appear more than one. Please advise if underscore.js can do deep watching of nested array of objects.

Please apologize me for the bad formatting of nested array of objects above.

like image 631
user12345 Avatar asked May 20 '26 02:05

user12345


1 Answers

function parse (levels)  {
  var buffer = [], target = [];
  levels.forEach(function (level) {
    buffer.push(level.path);
    if (!level.hasChild) {
      target.push(buffer.join('/'));
      buffer.splice(0, buffer.length + 1);
    }
  });
  return levels;  
}

Gives: [ 'RS/MO/EL/CL', 'EL1/CL1', 'RS2/MO2/EL2/CL2', 'CL3' ]

Given your current structure, the logic to get the desired output is unclear. How should the program know that RS2 starts a new node, but EL1 doesn't?

EDIT:

This solve the problem, but honestly, its hacky. A better way is to structure the data in a better way.

function parse (levels)  {
  var buffer = [], target = [];
  levels.forEach(function (level) {
    if (level.hasChild) {
      buffer.push(level.path);
    }
    else {
      var tmp = buffer.slice();
      tmp.push(level.path);
      target.push(tmp.join('/'));
      buffer.splice(buffer.length - 1, 1);
    }
    if (/^RS/.test(level.path)) {
      buffer.splice(1, buffer.length);
    }
  });
  return target;
}

Result: ['RS/MO/EL/CL', 'RS/MO/EL1/CL1', 'RS/MO2/EL2/CL2', 'RS/MO2/CL3']

like image 94
u.k Avatar answered May 22 '26 17:05

u.k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!