Selecting path field value from nested objects (parent) 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 a full path from the object level using underscore.js? Ex. -
RS \ MO \ EL \ CL
RS \ MO \ EL1 \ CL1
RS2 \ MO2 \ EL2 \ CL2
RS2 \ MO2 \ CL3 \ CL3
At any of the above levels, there may be more than one child. Please advise if underscore.js can deep scan a nested array of objects.
I apologize for the poor formatting of the nested array of objects above.
source to share
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 behind getting the desired result is unclear. How is a program supposed to know that RS2
a new node is starting up but EL1
not working?
EDIT:
This solves the problem, but honestly, it's a hack. The best way is to structure your data.
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']
source to share
use _.each for this
<i>
var path =""
_.each(levels,function(object){
path = path +object.path+"/"
})
console.log(path)
Output: "RS / MO / EL / CL / EL1 / CL1 / RS2 / MO2 / EL2 / CL2 / CL3 /"
Edit:
I think your Json shoud will be like this:
<i>
var levels = [
{
"path": "RS",
"hasChild": true,
"childerens": {
"path": "MO",
"hasChild": true,
"childe1": [
{
"path": "EL",
"hasChild": true
},
{
"path": "CL",
"hasChild": false
}
],
"childe2": [
{
"path": "EL1",
"hasChild": true
},
{
"path": "CL1",
"hasChild": false
}
]
},
"isParent": true
},
{
"path": "RS2",
"hasChild": true,
"childerens": {
"path": "MO2",
"hasChild": true,
"chiled1": [
{
"path": "EL2",
"hasChild": true
},
{
"path": "CL2",
"hasChild": false
}
],
"chiled2": [
{
"path": "CL3",
"hasChild": true
},
{
"path": "CL3",
"hasChild": false
}
]
},
"isParent": true
}
]
For json validation is wrong or go to JSONLINT correctly
Remove variable name to check
source to share