looping through JSON object with multiple childrens using java script - javascript

I am trying to loop through a Json object which would look like this
[
{
"yang_type": "container",
"name": "c1",
"value": "",
"children": [
{
"yang_type": "",
"name": "type",
"value": "Uint32",
"children": []
},
{
"yang_type": "list",
"name": "DNS",
"value": "",
"children": [
{
"name": "type",
"value": "String",
"children": [],
"yang_type": ""
},
{
"yang_type": "leaf",
"name": "ip-address",
"value": "",
"children": [
{
"name": "type",
"value": "string",
"children": [],
"yang_type": ""
}
]
},
{
"yang_type": "leaf",
"name": "Domain",
"value": "",
"children": [
{
"name": "type",
"value": "string",
"children": [],
"yang_type": ""
}
]
}
]
}
]
}
]
I am trying this logic but it doesnt loop through first childs child.
while(m.children.length >= 1) {
if(m.yang_type!='' && m.name!=''){
{$log.error("parent:",m.yang_type,m.name);}
}
if(m.name!='' && m.value!=''){
{$log.error("child:",m.name,m.value);}
}
m = m.children[m.children.length - 1];
}
The above code doesn't loop through all the children. what i am doing wrong ?

You try to loop over the array. Your attempt does not work this way.
You could use a callback for iterating and a take it for the recursive call for childrens.
function loop(a) {
console.log(a.name); // process you data
Array.isArray(a.children) && a.children.forEach(loop); // check and iterate children
}
var data = [{ "yang_type": "container", "name": "c1", "value": "", "children": [{ "yang_type": "", "name": "type", "value": "Uint32", "children": [] }, { "yang_type": "list", "name": "DNS", "value": "", "children": [{ "name": "type", "value": "String", "children": [], "yang_type": "" }, { "yang_type": "leaf", "name": "ip-address", "value": "", "children": [{ "name": "type", "value": "string", "children": [], "yang_type": "" }] }, { "yang_type": "leaf", "name": "Domain", "value": "", "children": [{ "name": "type", "value": "string", "children": [], "yang_type": "" }] }] }] }];
data.forEach(loop);
Edit with indented output.
function loop(level) {
return function (a) {
var i = level, s = '';
while (i--) {
s += ' ';
}
if (level) {
s += '*';
}
a.yang_type ?
console.log(s + a.yang_type + ' ' + a.name) :
console.log(s + a.name + ' ' + a.value);
Array.isArray(a.children) && a.children.forEach(loop(level + 1));
}
}
var data = [{ "yang_type": "container", "name": "c1", "value": "", "children": [{ "yang_type": "", "name": "type", "value": "Uint32", "children": [] }, { "yang_type": "list", "name": "DNS", "value": "", "children": [{ "name": "type", "value": "String", "children": [], "yang_type": "" }, { "yang_type": "leaf", "name": "ip-address", "value": "", "children": [{ "name": "type", "value": "string", "children": [], "yang_type": "" }] }, { "yang_type": "leaf", "name": "Domain", "value": "", "children": [{ "name": "type", "value": "string", "children": [], "yang_type": "" }] }] }] }];
data.forEach(loop(0));

Related

How to find the farthest object in a sub array of a array with empty objects?

I've got a array of object in which the children got arrays as well:
[{
"id": 0,
"name": "Primary",
"xPoints": [{
"id": 0,
"name": "Untitledtest12",
"type": "custom",
"description": ""
}, {
"id": 1,
"name": "asd",
"description": "",
"type": "custom"
}, {
"id": 2,
"name": "asd",
"description": "",
"type": "custom"
}, {
"id": 3,
"name": "asd123",
"description": "",
"type": "custom"
}, {
"id": 4,
"name": "a",
"description": "a",
"type": "custom"
}]
}, {
"id": 1,
"name": "Untitled X Line",
"xPoints": [
{},
{},
{},
{},
{},
{
"id": 0,
"name": "this is the farthest",
"type": "custom",
"description": ""
},
{}
]
}]
what I'm looking for is a way to get the "farthest" of object index on these childrens of the main array
Expected result:
index: 6 from second's "Untitled X Line"
You can use recursion to get the depth of the object.
const obj = [{
"id": 0,
"name": "Primary",
"xPoints": [{
"id": 0,
"name": "Untitledtest12",
"type": "custom",
"description": ""
}, {
"id": 1,
"name": "asd",
"description": "",
"type": "custom"
}, {
"id": 2,
"name": "asd",
"description": "",
"type": "custom"
}, {
"id": 3,
"name": "asd123",
"description": "",
"type": "custom"
}, {
"id": 4,
"name": "a",
"description": "a",
"type": "custom"
}]
}, {
"id": 1,
"name": "Untitled X Line",
"xPoints": [
{},
{},
{},
{},
{},
{
"id": 0,
"name": "this is the farthest",
"type": "custom",
"description": ""
},
{}
]
}]
function depthOf(object) {
var level = 1;
for(var key in object) {
if (!object.hasOwnProperty(key)) continue;
if(typeof object[key] == 'object'){
var depth = depthOf(object[key]) + 1;
level = Math.max(depth, level);
}
}
return level;
}
var maxLevels = 0;
var maxObj;
obj.forEach(e => maxLevels < depthOf(e) ? maxObj = e : '');
console.log(maxObj);

Add new property in object recursively

I have a recursive array with same structure of objects and it contains name property. My requirement is to add new property id along with name in recursive array of objects
below is my sample array
[
{
"children": [
{
"children": [
{
"children": [
{
"children": [],
"name": "ID01",
"type": "Under"
},
{
"children": [],
"name": "ID02",
"type": "Under"
}
],
"name": "httpgateway",
"type": "Gut"
},
{
"children": [
{
"children": [],
"name": "mock1",
"type": "Under"
},
{
"children": [],
"name": "mock2",
"type": "Under"
}
],
"name": "mock",
"type": "Gut"
}
],
"name": "23131",
"type": "SEV"
}
],
"name": "integration",
"type": "DataCenter"
},
{
"children": [
{
"children": [
{
"children": [
{
"children": [],
"name": "data1",
"type": "Under"
},
{
"children": [],
"name": "data12",
"type": "Under"
},
{
"children": [],
"name": "data13",
"type": "Under"
},
{
"children": [],
"name": "data14",
"type": "Under"
}
],
"name": "Gut1",
"type": "Gut"
}
],
"name": "213213",
"type": "SEV"
}
],
"name": "dev",
"type": "dt"
}
]
I need Id property along with name as belo
[
{
"children": [
{
"children": [
{
"children": [
{
"children": [],
"name": "ID01",
"id": "ID01",
"type": "Under"
},
{
"children": [],
"name": "ID02",
"id": "ID02",
"type": "Under"
}
],
"name": "gate",
"id": "gate",
"type": "Gut"
},
{
"children": [
{
"children": [],
"name": "mock1",
"id": "mock1",
"type": "Under"
},
{
"children": [],
"name": "mock2",
"id": "mock2",
"type": "Under"
}
],
"name": "mock",
"name": "id",
"type": "Gut"
}
],
"name": "23131",
"id": "23131",
"type": "SEV"
}
],
"name": "int",
"id": "int",
"type": "dt"
},
{
"children": [
{
"children": [
{
"children": [
{
"children": [],
"name": "data1",
"id": "data1",
"type": "Under"
},
{
"children": [],
"name": "data12",
"id": "data12",
"type": "Under"
}
],
"name": "Gut1",
"id": "Gut1",
"type": "Gut"
}
],
"name": "213213",
"id": "213213",
"type": "SEV"
}
],
"name": "dev",
"id": "dev",
"type": "dt"
}
]
I have written method to update this but its not working as expected
const getTreeItemsFromData = (treeItems) => {
console.log('---------------------------', treeItems)
let finalData = []
return treeItems.map((treeItemData) => {
let children = undefined;
if (treeItemData.children && treeItemData.children.length > 0) {
children = this.getTreeItemsFromData(treeItemData.children);
}
let uniqueId = `${treeItemData.name}${Math.floor(Math.random()*(999-100+1)+100)}`;
finalData.push(treeItemData)
console.log("-- ------------------", treeItemData)
});
};
You jus need a function to accept the array and check if the key children exists and is array, make changes to it and then recursively call if it has children.
const t = [
{
"children": [
{
"children": [
{
"children": [
{
"children": [
],
"name": "data1",
"type": "Under"
},
{
"children": [
],
"name": "data12",
"type": "Under"
},
{
"children": [
],
"name": "data13",
"type": "Under"
},
{
"children": [
],
"name": "data14",
"type": "Under"
}
],
"name": "Gut1",
"type": "Gut"
}
],
"name": "213213",
"type": "SEV"
}
],
"name": "dev",
"type": "dt"
}
];
function addIdRec(arr){
arr.forEach(a => {
if(a.children instanceof Array){
a.id = a.name;
if(a.children.length > 0){
addIdRec(a.children);
}
}
})
}
addIdRec(t)
We can do this with a pretty simple recursion:
const addId = (data) =>
data .map (({name, children, ...rest}) =>
({children: addId(children), name, id: name, ...rest})
)
const data = [{children: [{children: [{children: [{children: [], name: "ID01", type: "Under"}, {children: [], name: "ID02", type: "Under"}], name: "httpgateway", type: "Gut"}, {children: [{children: [], name: "mock1", type: "Under"}, {children: [], name: "mock2", type: "Under"}], name: "mock", type: "Gut"}], name: "23131", type: "SEV"}], name: "integration", type: "DataCenter"}, {children: [{children: [{children: [{children: [], name: "data1", type: "Under"}, {children: [], name: "data12", type: "Under"}, {children: [], name: "data13", type: "Under"}, {children: [], name: "data14", type: "Under"}], name: "Gut1", type: "Gut"}], name: "213213", type: "SEV"}], name: "dev", type: "dt"}]
console .log (addId (data))
.as-console-wrapper {max-height: 100% !important; top: 0}
We simply clone the node, adding an id property to match the name one and recur on the children property.

ES6 Object Mapping

I was working on something but stuck at a point where I have inputs as -
var definition = [
{
"name": "objA",
"type": "object",
"items": [
{
"value": "",
"name": "A"
},
{
"value": "",
"name": "B"
},
{
"value": "",
"name": "C"
}
]
},
{
"name": "objX",
"type": "object",
"items": [
{
"value": "",
"name": "X"
},
{
"value": "",
"name": "Y"
},
{
"value": "",
"name": "Z"
}
]
}
];
var data = {
"objA": {
"A": "ValA",
"B": "ValB",
"C": "ValC"
},
"objX": {
"X": "ValX",
"Y": "ValY",
"Z": "ValZ"
}
};
const updateSchema = (data, definition) => {
definition.forEach((subDef) => {
var node = data[subDef.name];
subDef.items.forEach((sub)=> {
sub.value = node[sub.name]
});
});
return definition;
}
console.log(updateSchema(data,definition))
The output I need is
[
{
"name": "objA",
"type": "object",
"items": [
{
"value": "valA",
"name": "A"
},
{
"value": "valB",
"name": "B"
},
{
"value": "valC",
"name": "C"
}
]
},
{
"name": "objX",
"type": "object",
"items": [
{
"value": "valX",
"name": "X"
},
{
"value": "valY",
"name": "Y"
},
{
"value": "valZ",
"name": "Z"
}
]
}
]
But it gives the output as -
[
{
"name": "objA",
"type": "object",
"items": [
{
"value": "ValX",
"name": "A"
},
{
"value": "ValY",
"name": "B"
},
{
"value": "ValY",
"name": "C"
}
]
},
{
"name": "objX",
"type": "object",
"items": [
{
"value": "ValX",
"name": "X"
},
{
"value": "ValY",
"name": "Y"
},
{
"value": "ValZ",
"name": "Z"
}
]
}
]
I am not able to know where I am doing wrong.
I am using React with typescript. I need to perform the above operation based on some API response.
I am prepopulating some value in the form based on the API response.
Try:
subDef.items.forEach((sub)=> {
sub.value = node[sub.name].charAt(0).toLowerCase() + node[sub.name].slice(1);
});
https://jsfiddle.net/j8nwpf6m/

JavaScript time comparison with arrays

I'm working on a project where I need to get all the vacant classrooms for the day and basically filter out the ones being in use.
I get all the data from the school's own API with JSON response body that looks like this:
{
"status": "success",
"reservations": [
{
"id": "18935",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:04:51",
"startDate": "2017-04-27T11:00:00",
"endDate": "2017-04-27T13:00:00",
"resources": [
{
"id": "50",
"type": "room",
"code": "A440.5",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A440.5"
},
{
"id": "2995",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "2267",
"type": "student_group",
"code": "",
"name": ""
}
],
"description": ""
},
{
"id": "20362",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:05:05",
"startDate": "2017-04-27T11:00:00",
"endDate": "2017-04-27T14:00:00",
"resources": [
{
"id": "51",
"type": "room",
"code": "A450.1",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A450.1"
},
{
"id": "2402",
"type": "student_group",
"code": "",
"name": ""
},
{
"id": "3064",
"type": "realization",
"code": "",
"name": ""
}
],
"description": ""
},
{
"id": "20237",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:05:05",
"startDate": "2017-04-27T11:15:00",
"endDate": "2017-04-27T13:00:00",
"resources": [
{
"id": "45",
"type": "room",
"code": "A420.4",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A420.4"
},
{
"id": "2433",
"type": "student_group",
"code": "",
"name": ""
},
{
"id": "3058",
"type": "realization",
"code": "",
"name": ""
}
],
"description": ""
},
{
"id": "20888",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:04:57",
"startDate": "2017-04-27T13:15:00",
"endDate": "2017-04-27T16:00:00",
"resources": [
{
"id": "62",
"type": "room",
"code": "A520.5",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A520.5"
},
{
"id": "3092",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "2444",
"type": "student_group",
"code": "",
"name": ""
}
],
"description": ""
},
{
"id": "22586",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:04:48",
"startDate": "2017-04-27T13:15:00",
"endDate": "2017-04-27T17:00:00",
"resources": [
{
"id": "52",
"type": "room",
"code": "A450.3",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A450.3"
},
{
"id": "3004",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "2294",
"type": "student_group",
"code": "",
"name": ""
},
{
"id": "525",
"type": "student_group",
"code": "",
"name": ""
}
],
"description": ""
},
{
"id": "18816",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:04:58",
"startDate": "2017-04-27T13:15:00",
"endDate": "2017-04-27T16:00:00",
"resources": [
{
"id": "41",
"type": "room",
"code": "A340.1",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A340.1"
},
{
"id": "2989",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "795",
"type": "student_group",
"code": "",
"name": ""
},
{
"id": "599",
"type": "student_group",
"code": "",
"name": ""
}
],
"description": ""
},
{
"id": "20431",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:04:56",
"startDate": "2017-04-27T13:15:00",
"endDate": "2017-04-27T16:00:00",
"resources": [
{
"id": "40",
"type": "room",
"code": "A320.7",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A320.7/8"
},
{
"id": "2416",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "2386",
"type": "student_group",
"code": "",
"name": ""
}
],
"description": ""
},
{
"id": "18588",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:04:49",
"startDate": "2017-04-27T13:15:00",
"endDate": "2017-04-27T16:00:00",
"resources": [
{
"id": "25",
"type": "room",
"code": "A130.1",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A130.1"
},
{
"id": "26",
"type": "room",
"code": "A130.3",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A130.3"
},
{
"id": "2979",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "582",
"type": "student_group",
"code": "",
"name": ""
}
],
"description": ""
},
{
"id": "18940",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:04:53",
"startDate": "2017-04-27T13:15:00",
"endDate": "2017-04-27T16:00:00",
"resources": [
{
"id": "2996",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "2267",
"type": "student_group",
"code": "",
"name": ""
},
{
"id": "2268",
"type": "student_group",
"code": "",
"name": ""
},
{
"id": "31",
"type": "room",
"code": "A210.2",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A210.2"
}
],
"description": ""
},
{
"id": "12041",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:04:53",
"startDate": "2017-04-27T14:15:00",
"endDate": "2017-04-27T17:00:00",
"resources": [
{
"id": "2510",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "775",
"type": "student_group",
"code": "",
"name": ""
},
{
"id": "23",
"type": "room",
"code": "A520.7",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A520.7"
}
],
"description": ""
},
{
"id": "24630",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:05:05",
"startDate": "2017-04-27T14:15:00",
"endDate": "2017-04-27T17:00:00",
"resources": [
{
"id": "3277",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "42",
"type": "room",
"code": "A340.2",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A340.2"
}
],
"description": ""
},
{
"id": "27205",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:05:07",
"startDate": "2017-04-27T14:15:00",
"endDate": "2017-04-27T17:00:00",
"resources": [
{
"id": "35",
"type": "room",
"code": "A240.2",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A240.2"
},
{
"id": "775",
"type": "student_group",
"code": "",
"name": ""
},
{
"id": "3384",
"type": "realization",
"code": "",
"name": ""
}
],
"description": ""
},
{
"id": "25917",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:05:00",
"startDate": "2017-04-27T15:15:00",
"endDate": "2017-04-27T16:00:00",
"resources": [
{
"id": "36",
"type": "room",
"code": "A240.4",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A240.4"
},
{
"id": "593",
"type": "realization",
"code": "",
"name": ""
},
{
"id": "595",
"type": "student_group",
"code": "",
"name": ""
}
],
"description": ""
},
{
"id": "21932",
"subject": "subjectName",
"modifiedDate": "2017-04-27T06:05:06",
"startDate": "2017-04-27T16:00:00",
"endDate": "2017-04-27T18:00:00",
"resources": [
{
"id": "43",
"type": "room",
"code": "A350.1",
"parent": {
"id": "2",
"type": "building",
"code": "A",
"name": "buildingA"
},
"name": "A350.1"
},
{
"id": "2464",
"type": "student_group",
"code": "",
"name": ""
},
{
"id": "2747",
"type": "student_group",
"code": "",
"name": ""
}
],
"description": ""
}
]
}
In order to get the JSON response I need to put startDate (the moment user searches the vacant rooms, in this situation it is: 2017-04-27T10:55) and endDate (set to end of the day, 2017-04-27T22:00). The result for this query is the JSON response above.
The problem is that the API I'm using doesn't contain any data for the vacant rooms but only for the ones booked for certain times so I made a list of all the rooms in the building and compared it to the booked ones to filter them out:
var rooms = ['A120.3', 'A130.1', 'A130.3', 'A140.1', 'A140.2', 'A140.4', 'A250.1', 'A240.4', 'A240.2', 'A220.5', 'A220.3',
'A220.1', 'A210.2', 'A320.2', 'A320.6', 'A320.7', 'A320.8', 'A340.1', 'A340.2', 'A350.1', 'A350.3', 'A440.5', 'A450.3','A450.1',
'A440.4', 'A440.2', 'A420.6', 'A420.5', 'A420.4', 'A420.2', 'A510.2', 'A520.5', 'A510.4', 'A520.6', 'A520.7','A540.1', 'A540.2'];
var data = JSON.parse(responseText);
var booking = Object.create(null);
var free;
data.reservations.forEach(function (reservation) {
reservation.resources.some(function (resource) {
if (resource.type === 'room') {
booking[resource.code] = booking[resource.code] || [];
booking[resource.code].push({ startDate: reservation.startDate, endDate: reservation.endDate });
return true;
}
});
});
free = rooms.filter(function (a) {
return !booking[a];
});
console.log(free);
Results:
A210.3
A220.5
A320.2
A520.6
A510.4
This only returns the ones that are not being used at all during the day but I need to get the ones that are vacant for hour or two.
For this booked class for example:
"startDate": "2017-04-27T13:15:00",
"endDate": "2017-04-27T16:00:00",
"type": "room",
"code": "A520.5"
for this I would need to print out:
A520.5 - 2 hours 20 minutes
So I need to get the room / time from the startDate of the search (2017-04-27T10:55) and compare it to the startDate of the booked room (2017-04-27T13:15:00) to get the time remaining for that room to be vacant.
TO CLARIFY:
I have all the data for booked rooms starting from 2017-04-27T10:55
until 2017-04-27T22:00 as you can see from the JSON response above.
I need to somehow compare the startDate of the JSON query when the user
searches for the rooms (2017-04-27T10:55) and compare it to the booked
rooms startDate to get the time how long the room stays vacant.
This is how I'm doing my startDate and endDate for the JSON query:
// Timestamp needs to be formed (YYYY-MM-DDTxx:xx) in order for JSON query to work
var todaysDate = new Date();
function convertDate(date) {
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth() + 1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1] ? mm : "0" + mmChars[0]) + '-' + (ddChars[1] ? dd : "0" + ddChars[0]);
}
// Current time when user searches for vacant rooms
var currentTime = new Date();
var time = "T" + currentTime.getHours() + ":" + currentTime.getMinutes();
// variables for the JSON query
var startDate = convertDate(todaysDate) + time;
var endDate = convertDate(todaysDate) + ("T22:00");
// JSON-query
var getRooms = {
"startDate": startDate,
"endDate": endDate
};

Traverse Object and build Tree Lineage

Json Object :
var json = {
"Tree": [{
"Title": "Condition",
"Attr": {
"Id": 2258,
"Zone": null
},
"Children": [{
"Title": "General Wellness",
"Attr": {
"Id": 2315,
"Zone": null
},
"Children": [{
"Title": "Family Health",
"Attr": {
"Id": 2262,
"Zone": null
},
"Children": []
}, {
"Title": "Healthy Home",
"Attr": {
"Id": 2316,
"Zone": null
},
"Children": []
}, {
"Title": "Vitamins",
"Attr": {
"Id": 2317,
"Zone": null
},
"Children": []
}, {
"Title": "Recipes",
"Attr": {
"Id": 2318,
"Zone": null
},
"Children": []
}, {
"Title": "Caregiving",
"Attr": {
"Id": 2325,
"Zone": null
},
"Children": []
}, {
"Title": "Healthy Eating",
"Attr": {
"Id": 2346,
"Zone": null
},
"Children": []
}, {
"Title": "Travel Health",
"Attr": {
"Id": 2347,
"Zone": null
},
"Children": []
}]
}]
}]
}
I am able to traverse the tree however I am unable to build a tree structure for example if I wanted to look for "Recipes" it should return me the result as :
Condition > General Wellness > Recipes
UPDATE :
Traversing is done via :
function process(key,value) {
alert(key + " : "+value);
}
function traverse(o,func) {
for (var i in o) {
func.apply(this,[i,o[i]]);
if (o[i] !== null && typeof(o[i])=="object") {
traverse(o[i],func);
}
}
}
traverse(json,process);
I suggest an iterative, as you already had, approach with a defined exit if found and a repeated calling if not found. The path is created if the target is found.
Bonus: The getPath returns the success of the search.
function getPath(array, target, path) {
return array.some(function (a) {
if (a.Title === target) {
return path.unshift(a.Title);
} else if (Array.isArray(a.Children)) {
return getPath(a.Children, target, path) && path.unshift(a.Title);
}
});
}
var data = {
"Tree": [{
"Title": "Condition",
"Attr": {
"Id": 2258,
"Zone": null
},
"Children": [{
"Title": "General Wellness",
"Attr": {
"Id": 2315,
"Zone": null
},
"Children": [{
"Title": "Family Health",
"Attr": {
"Id": 2262,
"Zone": null
},
"Children": []
}, {
"Title": "Healthy Home",
"Attr": {
"Id": 2316,
"Zone": null
},
"Children": []
}, {
"Title": "Vitamins",
"Attr": {
"Id": 2317,
"Zone": null
},
"Children": []
}, {
"Title": "Recipes",
"Attr": {
"Id": 2318,
"Zone": null
},
"Children": []
}, {
"Title": "Caregiving",
"Attr": {
"Id": 2325,
"Zone": null
},
"Children": []
}, {
"Title": "Healthy Eating",
"Attr": {
"Id": 2346,
"Zone": null
},
"Children": []
}, {
"Title": "Travel Health",
"Attr": {
"Id": 2347,
"Zone": null
},
"Children": []
}]
}]
}, {
Title: 'abc',
Children: [{
Title: 'def',
Children: [{
Title: 'ghi'
}]
}, {
Title: 'jkl',
Children: [{
Title: 'mno'
}]
}]
}]
},
path = [];
document.write(getPath(data.Tree, 'Recipes', path) + ': ' + path.join(' > ') + '<br>');
path = [];
document.write(getPath(data.Tree, 'ghi', path) + ': ' + path.join(' > ') + '<br>');
path = [];
document.write(getPath(data.Tree, 'nonsense', path) + ': ' + path.join(' > ') + '<br>');

Categories

Resources