Flattening hierarchical json data for table display - javascript

this is the basic structure of tree:
{
"DescId" : "1",
"Desc" : "Parent 1",
"ParentId" : "null",
"Order" : 1.0,
"Type" : "A",
"Parent" : null,
"Depth" : 0.0
}
{
"DescId" : "1.1",
"Desc" : "Child 1",
"ParentId" : "1",
"Order" : 1.0,
"Type" : "B",
"Parent" : "Parent 1",
"Depth" : 1.0
}
{
"DescId" : "1.2",
"Desc" : "Child 2",
"ParentId" : "1",
"Order" : 2.0,
"Type" : "B",
"Parent" : "Parent 1",
"Depth" : 1.0
}
{
"DescId" : "1.1.1",
"Desc" : "Grand Child 1",
"ParentId" : "1.1",
"Order" : 1.0,
"Type" : "C",
"Parent" : "Child 1",
"Depth" : 2.0
}
{
"DescId" : "1.1.1.1",
"Desc" : "Great Grand Child 1",
"ParentId" : "1.1.1",
"Order" : 1.0,
"Type" : "D",
"Parent" : "Grand Child 1",
"Depth" : 3.0
}
{
"DescId" : "2",
"Desc" : "Parent 2",
"ParentId" : null,
"Order" : 2.0,
"Type" : "A",
"Parent" : null,
"Depth" : 0.0
}
I have this hierarchical json data as below:
[
{
"DescId": "1",
"Desc": "Parent 1",
"Type": "A",
"children": [
{
"DescId": "1.2",
"Desc": "Child 2",
"ParentId": "1",
"Order": 2,
"Type": "B",
"Parent": "Parent 1",
"Depth": 1
},
{
"DescId": "1.1",
"Desc": "Child 1",
"ParentId": "1",
"Order": 1,
"Type": "B",
"Parent": "Parent 1",
"Depth": 1
}
]
},
{
"DescId": "1.1",
"Desc": "Child 1",
"Type": "B",
"children": [
{
"DescId": "1.1.1",
"Desc": "Grand Child 1",
"ParentId": "1.1",
"Order": 1,
"Type": "C",
"Parent": "Child 1",
"Depth": 2
}
]
},
{
"DescId": "1.2",
"Desc": "Child 2",
"Type": "B",
"children": []
},
{
"DescId": "1.1.1",
"Desc": "Grand Child 1",
"Type": "Consequence",
"children": [
{
"DescId": "1.1.1.1",
"Desc": "Great Grand Child 1",
"ParentId": "1.1.1",
"Order": 1.0,
"Type": "D",
"Parent": "Grand Child 1",
"Depth": 3.0
}
]
},
{
"DescId": "1.1.1.1",
"Desc": "Great Grand Child 1",
"Type": "D",
"children": []
},
{
"DescId": "2",
"Desc": "Parent 2",
"Type": "A",
"children": []
}
]
I have this requirement where I need to display this hierarchical tree as a tabular structure.
So data needs to be like below:
[
{
"A" + "DescId" : "1",
"A" + "Desc" : "Parent",
"B" + "DescId" : "1.1",
"B" + "Desc" : "Child 1,
"C" + "DescId" : "1.1.1",
"C" + "Desc" : "Grand Child 1"
"D" + "DescId" : "1.1.1.1",
"D" + "Desc" : "Great Grand child 1"
},
{
"A" + "DescId" : "1",
"A" + "Desc" : "Parent 1",
"B" + "DescId" : "1.2"
"B" + "Desc" : "Child 2
//if there are any further generations like 1.2.1 or 1.2.1.1 should be present here
},
{
"A" + "DescId" : "2",
"A" + "Desc" : "Parent 2"
}
]
I have tried this code below in javascript and lodash:
function reformatData(sentData) {
var finalData = {};
var returnArray = [];
if (sentData.length > 0) {
var propertyNameArray = Object.keys(sentData[0]);
for (var i = 0; i < sentData.length; i++) {
var type = sentData[i].Type;
finalData[type + propertyNameArray[0]] = sentData[i].DescId;
finalData[type + propertyNameArray[1]] = sentData[i].Desc;
if (sentData[i].children && sentData[i].children.length > 0) {
var children = _.orderBy(sentData[i].children, ['Order'], ['asc']);
reformatData(children);
}
}
}
returnArray.push(finalData);
return returnArray;
}
The above code is ignoring first parent and adding only next available one. Could anyone help me pointing out what I am missing here. Below is the output code is generating:
[
{
"ADescid":"2",
"ADesc":"Parent 2",
"BDescid":"1.2",
"BDesc":"Child 2",
"CDescid":"1.1.1",
"CDesc":"Grand Child 1",
"DDescid":"1.1.1.1",
"DDesc":"Great grand child 1"
}
]

This proposal works in three steps:
Build the tree.
Collect all nodes to the final leaves.
Generate single objects with wanted keys as final result.
function getTree(array, root) {
var o = {};
array.forEach(function (a) {
o[a.DescId] = Object.assign({}, a, o[a.DescId]);
o[a.ParentId] = o[a.ParentId] || {};
o[a.ParentId].children = o[a.ParentId].children || [];
o[a.ParentId].children.push(o[a.DescId]);
});
return o[root].children;
}
function getLeafes(tree) {
var result = [];
tree.forEach(function iter(temp) {
return function ({ DescId, Desc, Type, children }) {
var t = temp.concat({ DescId, Desc, Type });
if (!children) {
result.push(t);
return;
}
children.forEach(iter(t));
};
}([]));
return result;
}
var nodes = [{ DescId: "1", Desc: "Parent 1", ParentId: "null", Order: 1, Type: "A", Parent: null, Depth: 0 }, { DescId: "1.1", Desc: "Child 1", ParentId: "1", Order: 1, Type: "B", Parent: "Parent 1", Depth: 1 }, { DescId: "1.2", Desc: "Child 2", ParentId: "1", Order: 2, Type: "B", Parent: "Parent 1", Depth: 1 }, { DescId: "1.1.1", Desc: "Grand Child 1", ParentId: "1.1", Order: 1, Type: "C", Parent: "Child 1", Depth: 2 }, { DescId: "1.1.1.1", Desc: "Great Grand Child 1", ParentId: "1.1.1", Order: 1, Type: "D", Parent: "Grand Child 1", Depth: 3 }, { DescId: "2", Desc: "Parent 2", ParentId: null, Order: 2, Type: "A", Parent: null, Depth: 0 }],
tree = getTree(nodes, null),
leaves = getLeafes(tree),
result = leaves.map(a => a.reduce((o, { DescId, Desc, Type }) => Object.assign(o, { [Type + 'DescId']: DescId, [Type + 'Desc']: Desc }), {}));
console.log(tree);
console.log(leaves);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

That can be solved in a quite elegant way with an recursive generator function:
function* paths(node, parent = {}) {
const current = {
...parent,
[node.type + "DescId"]: node.DescId,
[node.type + "Desc"]: node.Desc,
};
if(node.children && node.children.length) {
for(const child of node.children)
yield* paths(child, current);
} else {
yield current;
}
}
// The following is only needed as your root is an array not a node
function* pathArray(array) {
for(const el of array) yield* paths(el);
}
So you can call it as:
const result = [...pathArray(yourTreeArray)];

Related

Finding ID in nested array of objects

I'm still new to recursive functions but I'm having trouble returning the object once found to a variable (currently searching based on ID). I've included a dataset below and what I have so far. The recursive function finds the correct matching item, but when it returns it, it just returns undefined to the variable. I have tried the solution here and also get the same problem I have where it just returns undefined instead of the object. Any help/pointers would be great!
const data = {
"navItems": [
{
"type": "directory",
"id" : 1,
"name": "Nav Title 1",
"children": [
{
"downloadUrl": "",
"content": "",
"id" : 2,
"type": "file",
"name": "File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 3,
"name": "File 2.pdf"
},
{
"type": "directory",
"name": "Sub Title 1",
"id" : 4,
"children": [
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 5,
"name": "Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 6,
"name": "Sub File 2.docx"
}
]
},
{
"type": "directory",
"name": "Sub Title 2",
"id" : 7,
"children": [
{
"type": "directory",
"id" : 8,
"name": "Sub Sub Title 1",
"children": [
{
"downloadUrl": "",
"id" : 9,
"content": "",
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 10,
"name": "Sub Sub File 2.pdf"
}
]
},
{
"type": "directory",
"name": "Sub Sub Title 2",
"id" : 11,
"children": [
{
"downloadUrl": "",
"content": "",
"id" : 12,
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"id" : 13,
"type": "file",
"name": "Sub Sub File 2.pdf"
}
]
}
]
}
]
}
]
}
/* console.log(navigationConfig);*/
const searchNavItems = (navItem) => {
if (navItem.id == 10) {
console.log(navItem);
return navItem;
} else {
if (navItem.hasOwnProperty("children") && navItem.children.length > 0 && navItem.type == "directory") {
navItem.children.map(child => searchNavItems(child))
} else {
return false;
}
}
};
let dataItem = data.navItems.forEach((item => {
let nav = searchNavItems(item);
console.log(nav);
}))
console.log(dataItem)
in your fn there are couple of problems
when you are maping over children you are not returning the array of children
forEach does not return anything () => void, so you will need to create a new variable to hold that value
let dataItem;
data.navItems.forEach((item) => {
console.log(searchNavItems(item));
dataItem = searchNavItems(item);
});
hope this helps
Presented below is one possible way to achieve the desired objective.
Code Snippet
const mySearch = (needle, hayStack) => (
hayStack.some(({ id }) => id === needle)
? (
{children, ...rest} = hayStack.find(({ id }) => id === needle),
[{...rest}]
)
: hayStack.flatMap(
({ children = [] }) => mySearch(needle, children)
)
);
/* explanation of the above method
// method to search for element/s with given "id"
// finding "needle" (ie "id") in hayStack (ie, "array" of objects)
const mySearch = (needle, hayStack) => (
// check if needle exists in current array
hayStack.some(({ id }) => id === needle)
? ( // find the matching array elt, destructure to access
// "children" and "rest" props.
// send the props other than "children"
{children, ...rest} = hayStack.find(({ id }) => id === needle),
[{...rest}]
) // if needle is not present in current array
// try searching in the inner/nested "children" array
: hayStack.flatMap( // use ".flatMap()" to avoid nested return
// recursive call to "mySearch" with "children" as the hayStack
({ children = [] }) => mySearch(needle, children)
)
);
*/
const data = {
"navItems": [{
"type": "directory",
"id": 1,
"name": "Nav Title 1",
"children": [{
"downloadUrl": "",
"content": "",
"id": 2,
"type": "file",
"name": "File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 3,
"name": "File 2.pdf"
},
{
"type": "directory",
"name": "Sub Title 1",
"id": 4,
"children": [{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 5,
"name": "Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 6,
"name": "Sub File 2.docx"
}
]
},
{
"type": "directory",
"name": "Sub Title 2",
"id": 7,
"children": [{
"type": "directory",
"id": 8,
"name": "Sub Sub Title 1",
"children": [{
"downloadUrl": "",
"id": 9,
"content": "",
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 10,
"name": "Sub Sub File 2.pdf"
}
]
},
{
"type": "directory",
"name": "Sub Sub Title 2",
"id": 11,
"children": [{
"downloadUrl": "",
"content": "",
"id": 12,
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"id": 13,
"type": "file",
"name": "Sub Sub File 2.pdf"
}
]
}
]
}
]
}]
};
console.log(
'data for id: 10\n',
mySearch(10, data.navItems)?.[0]
);
console.log(
'data for id: 13\n',
mySearch(13, data.navItems)?.[0]
);
console.log(
'data for id: 9\n',
mySearch(9, data.navItems)?.[0]
);
console.log(
'data for id: 3\n',
mySearch(3, data.navItems)?.[0]
);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added to the snippet above.

Toggle property of nested array of object - JS

I have an array of objects with 3 levels. I want to target the innermost child with property 'code'. If code is present, then update the child as well as the parent object with selected: true. If the property already is true, then sending in the same value should set the child to selected: false (toggle)
This is what I have going so far. If selected is true for a child, sending in another code should set selected: true for the corresponding child and selected: false for the child which had true for selected property.
Also, if selected is true for a child, defaultCollapsed property should be false for the child as well as parent and grandparent. Ifs elected is false for a child, defaultCollapsed property should be true for the child as well as parent and grandparent
const data = [{
"label": "Grand Parent 1",
"index": 0,
"code": "GRAND_PARENT_1",
"defaultCollapsed": true,
"items": [{
"id": 1,
"items": [{
"id": 100,
"label": "Child 1",
"url": "#CHILD_1",
"code": "CHILD_1",
},
{
"id": 200,
"label": "Child 2",
"url": "#CHILD_2",
"code": "CHILD_2"
},
{
"id": 300,
"label": "Child 3",
"url": "#CHILD_3",
"code": "CHILD_3"
},
{
"id": 400,
"label": "Child 4",
"url": "#CHILD_4",
"code": "CHILD_4"
}
],
"defaultCollapsed": true,
"label": "Parent 1",
"selected": true,
},
{
"id": 2,
"items": [],
"defaultCollapsed": true,
"label": "Parent 2"
},
{
"id": 3,
"items": [],
"defaultCollapsed": true,
"label": "Parent 3"
},
{
"id": 4,
"items": [],
"defaultCollapsed": true,
"label": "Parent 4"
}
]
},
{
"label": "Grand Parent 2",
"index": 1,
"code": "GRAND_PARENT_2",
"defaultCollapsed": true,
"items": []
},
{
"label": "Grand Parent 3",
"index": 2,
"code": "GRAND_PARENT_3",
"defaultCollapsed": true,
"items": []
}
]
function select(items, key, value) {
if (!Array.isArray(items)) {
return false;
}
for (const item of items) {
if (item.code === value || select(item.items, key, value)) {
item.selected = !item.selected;
item.defaultCollapsed = false;
return true;
}
}
return false;
}
function reset(items) {
if (!Array.isArray(items)) {
return;
}
for (const item of items) {
if (item.selected) {
reset(item.items);
item.selected = false;
break;
}
}
}
function resetAndSelect(data, key, value) {
reset(data);
select(data, key, value);
}
resetAndSelect(data, 'code', 'CHILD_1')
console.log('CHILD_1',data)
resetAndSelect(data, 'code', 'CHILD_2')
console.log('CHILD_2',data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
If code is CHILD_1:
[{
"label": "Grand Parent 1",
"index": 0,
"code": "GRAND_PARENT_1",
"defaultCollapsed": true,
"selected": true,
"items": [{
"id": 1,
"items": [{
"id": 100,
"label": "Child 1",
"url": "#CHILD_1",
"code": "CHILD_1",
"selected": true,
},
{
"id": 200,
"label": "Child 2",
"url": "#CHILD_2",
"code": "CHILD_2"
},
{
"id": 300,
"label": "Child 3",
"url": "#CHILD_3",
"code": "CHILD_3"
},
{
"id": 400,
"label": "Child 4",
"url": "#CHILD_4",
"code": "CHILD_4"
}
],
"defaultCollapsed": false,
"label": "Parent 1",
"selected": true,
},
{
"id": 2,
"items": [],
"defaultCollapsed": true,
"label": "Parent 2"
},
{
"id": 3,
"items": [],
"defaultCollapsed": true,
"label": "Parent 3"
},
{
"id": 4,
"items": [],
"defaultCollapsed": true,
"label": "Parent 4"
}
]
},
{
"label": "Grand Parent 2",
"index": 1,
"code": "GRAND_PARENT_2",
"defaultCollapsed": true,
"items": []
},
{
"label": "Grand Parent 3",
"index": 2,
"code": "GRAND_PARENT_3",
"defaultCollapsed": true,
"items": []
}
]
If the above output is the actual data, and the code is CHILD_1 again, I need to toggle the selected property of the child as well the corresponding parents.
[{
"label": "Grand Parent 1",
"index": 0,
"code": "GRAND_PARENT_1",
"defaultCollapsed": true,
"selected": false,
"items": [{
"id": 1,
"items": [{
"id": 100,
"label": "Child 1",
"url": "#CHILD_1",
"code": "CHILD_1",
"selected": false,
},
{
"id": 200,
"label": "Child 2",
"url": "#CHILD_2",
"code": "CHILD_2"
},
{
"id": 300,
"label": "Child 3",
"url": "#CHILD_3",
"code": "CHILD_3"
},
{
"id": 400,
"label": "Child 4",
"url": "#CHILD_4",
"code": "CHILD_4"
}
],
"defaultCollapsed": false,
"label": "Parent 1",
"selected": false,
},
{
"id": 2,
"items": [],
"defaultCollapsed": true,
"label": "Parent 2"
},
{
"id": 3,
"items": [],
"defaultCollapsed": true,
"label": "Parent 3"
},
{
"id": 4,
"items": [],
"defaultCollapsed": true,
"label": "Parent 4"
}
]
},
{
"label": "Grand Parent 2",
"index": 1,
"code": "GRAND_PARENT_2",
"defaultCollapsed": true,
"items": []
},
{
"label": "Grand Parent 3",
"index": 2,
"code": "GRAND_PARENT_3",
"defaultCollapsed": true,
"items": []
}
]
You can do this by creating recursive function using forEach loop and passing array of parents down with recursion so that you can update its selected property.
const data = [{"label":"Grand Parent 1","index":0,"code":"GRAND_PARENT_1","defaultCollapsed":true,"items":[{"id":1,"items":[{"id":100,"label":"Child 1","url":"#CHILD_1","code":"CHILD_1"},{"id":200,"label":"Child 2","url":"#CHILD_2","code":"CHILD_2"},{"id":300,"label":"Child 3","url":"#CHILD_3","code":"CHILD_3"},{"id":400,"label":"Child 4","url":"#CHILD_4","code":"CHILD_4"}],"defaultCollapsed":true,"label":"Parent 1","selected":true},{"id":2,"items":[],"defaultCollapsed":true,"label":"Parent 2"},{"id":3,"items":[],"defaultCollapsed":true,"label":"Parent 3"},{"id":4,"items":[],"defaultCollapsed":true,"label":"Parent 4"}]},{"label":"Grand Parent 2","index":1,"code":"GRAND_PARENT_2","defaultCollapsed":true,"items":[]},{"label":"Grand Parent 3","index":2,"code":"GRAND_PARENT_3","defaultCollapsed":true,"items":[]}]
function update(data, key, value, parents = []) {
data.forEach(e => {
if (e[key] === value) {
if (parents.length) {
e.selected = !e.selected;
parents.forEach(p => {
p.defaultCollapsed = !e.selected
p.selected = e.selected
})
data.forEach(s => {
if (s != e && s.selected) s.selected = false;
});
}
}
if (e.items && e.items.length) {
update(e.items, key, value, [...parents, e])
}
})
}
update(data, 'code', 'CHILD_4')
update(data, 'code', 'CHILD_4')
update(data, 'code', 'CHILD_2')
update(data, 'code', 'CHILD_1')
console.log(data)
You could toggle the target node and leave the rest as true, for the path to the item.
function update(array, value) {
var found = false;
array.forEach(o => {
var sub = update(o.items || [], value),
check = o.code === value;
if (check) {
o.selected = !o.selected
found = o.selected;
} else {
o.selected = sub;
if (sub) found = o.selected;
}
o.defaultCollapsed = !o.selected;
});
return found;
}
var data = [{ label: "Grand Parent 1", index: 0, code: "GRAND_PARENT_1", defaultCollapsed: true, items: [{ id: 1, items: [{ id: 100, label: "Child 1", url: "#CHILD_1", code: "CHILD_1" }, { id: 200, label: "Child 2", url: "#CHILD_2", code: "CHILD_2" }, { id: 300, label: "Child 3", url: "#CHILD_3", code: "CHILD_3" }, { id: 400, label: "Child 4", url: "#CHILD_4", code: "CHILD_4" }], defaultCollapsed: false, label: "Parent 1" }, { id: 2, items: [], defaultCollapsed: true, label: "Parent 2" }, { id: 3, items: [], defaultCollapsed: true, label: "Parent 3" }, { id: 4, items: [], defaultCollapsed: true, label: "Parent 4" }] }, { label: "Grand Parent 2", index: 1, code: "GRAND_PARENT_2", defaultCollapsed: true, items: [] }, { label: "Grand Parent 3", index: 2, code: "GRAND_PARENT_3", defaultCollapsed: true, items: [] }];
update(data, 'CHILD_1');
console.log(data);
update(data, 'CHILD_1');
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

jsTree - is_parent() returning wrong value

I'm requesting data from a remote server with json return in format :
[
{"id":"1", "parent": "#", "text" : "Parent1"},
{"id":"2", "parent": 1, "text" : "Child1"}
{"id":"3", "parent": 2, "text" : "Child12"}
{"id":"4", "parent": 1, "text" : "Child2"}
{"id":"5", "parent": 1, "text" : "Child3"}
{"id":"6", "parent": 4, "text" : "Child21"}
]
I would like to check if the selected node is a parent. I use this code:
$('#treeview').on("select_node.jstree", function (e, data) {
var isParent = data.instance.is_parent();
alert(isParent)
});
It always returns false even when I click on PARENT.
What am I missing here ?
UPDATE
This is how I get solved the issue. But I still wonder why the methods is_parent() and is_leaf() are not working
var isParent = (data.node.children.length > 0);
To get parent
use
var isParent = (data.node.children.length > 0);
alert(isParent );
$('#treeview').jstree({
'core': {
'data': [{
"id": "1",
"parent": "#",
"text": "Parent1"
}, {
"id": "2",
"parent": 1,
"text": "Child1"
},
{
"id": "21",
"parent": 2,
"text": "Child1"
},
{
"id": "3",
"parent": 2,
"text": "Child12"
}, {
"id": "4",
"parent": 1,
"text": "Child2"
}, {
"id": "5",
"parent": 1,
"text": "Child3"
},
{
"id": "6",
"parent": 4,
"text": "Child21"
},
{
"id": "7",
"parent": '#',
"text": "Parent 2"
},
{
"id": "8",
"parent": 7,
"text": "Child"
}
]
}
});
$('#treeview').on("select_node.jstree", function(e, data) {
// var isParent = data.instance.is_parent(data);
// If you need to check if a node is a root node you can use:
var isParent = (data.node.children.length > 0);
console.log(data.node);
alert(isParent)
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<div id="treeview"></div>

Count length of items in nested js object

Given an array like this, how would I get a count of all charts in a particular category. Each category can have multiple or no groups.
{
"categories":[
{
"title":"category 1",
"id":"cat1",
"groups":[
{
"title":"group 1",
"id":"grp1",
"charts":[
{
"title":"chart 1",
"id":"chart1",
"type":"line"
}
]
}
]
},
{
"title":"category 2",
"id":"cat2",
"charts":[
{
"title":"chart 2",
"id":"chart2",
"type":"line"
}
]
},
{
"title":"category 3",
"id":"cat3",
"charts":[
{
"title":"chart 3",
"id":"chart3",
"type":"line"
}
]
}
]
}
Is a one-liner okay?
Assuming data is your JSON structure:
data.categories
.map(c => [
c.title,
c.groups ?
c.groups.map(g => g.charts.length).reduce((a, b) => a+b) :
c.charts.length
])
var object = {
"categories": [{
"title": "category 1",
"id": "cat1",
"groups": [{
"title": "group 1",
"id": "grp1",
"charts": [{
"title": "chart 1",
"id": "chart1",
"type": "line"
}]
}]
}, {
"title": "category 2",
"id": "cat2",
"charts": [{
"title": "chart 2",
"id": "chart2",
"type": "line"
}]
}, {
"title": "category 3",
"id": "cat3",
"charts": [{
"title": "chart 3",
"id": "chart3",
"type": "line"
}]
}]
}
var groupPerCategories = [];
object.categories.forEach(function(category) {
var tot = 0;
if (category.groups != undefined) {
category.groups.forEach(function(group) {
if(group.charts != undefined){
tot += group.charts.length;
}
});
}
if (category.charts != undefined) {
tot += category.charts.length;
}
console.log(tot);
});
You could count the properties with default.
var data = { "categories": [{ "title": "category 1", "id": "cat1", "groups": [{ "title": "group 1", "id": "grp1", "charts": [{ "title": "chart 1", "id": "chart1", "type": "line" }] }] }, { "title": "category 2", "id": "cat2", "charts": [{ "title": "chart 2", "id": "chart2", "type": "line" }] }, { "title": "category 3", "id": "cat3", "charts": [{ "title": "chart 3", "id": "chart3", "type": "line" }] }] },
count = {};
data.categories.forEach(function (a) {
var countCharts = function (r, a) {
return r + (a.charts || []).length;
};
count[a.title] = (count[a.title] || 0) +
(a.groups ||[]).reduce(countCharts, 0) +
countCharts(0, a);
});
console.log(count);
Hope this will help you :)
var categories = [
{
"title":"category 1",
"id":"cat1",
"groups":[
{
"title":"group 1",
"id":"grp1",
"charts":[
{
"title":"chart 1",
"id":"chart1",
"type":"line"
}
]
}
]
},
{
"title":"category 2",
"id":"cat2",
"charts":[
{
"title":"chart 2",
"id":"chart2",
"type":"line"
}
]
},
{
"title":"category 3",
"id":"cat3",
"charts":[
{
"title":"chart 3",
"id":"chart3",
"type":"line"
},
{
"title":"chart 3",
"id":"chart3",
"type":"line"
},
{
"title":"chart 3",
"id":"chart3",
"type":"line"
}
]
},
{
"title":"category 4",
"id":"cat4",
"groups":[
{
"title":"group 4",
"id":"grp4",
"charts":[
{
"title":"chart 1",
"id":"chart1",
"type":"line"
},
{
"title":"chart 1",
"id":"chart1",
"type":"line"
}
]
}
]
}
];
function countCategoryItems(data, category) {
if(!data ) return 0
if(!category) return 0
var cat = _.filter(data, function(obj){ return obj.title == category; });
if(!cat.length) return 0
var groups = cat[0].groups || []
if(!groups.length) return cat[0].charts.length
var count = 0
for (var i=0;i<groups.length;i++) {
count += groups[i].charts.length
}
return count
}
$(function() {
console.log(countCategoryItems(categories, 'category 1'))
console.log(countCategoryItems(categories, 'category 2'))
console.log(countCategoryItems(categories, 'category 3'))
console.log(countCategoryItems(categories, 'category 4'))
})
<script src="http://underscorejs.org/underscore.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

D3 tree/hierachical related data between nodes

I am working on a d3 project at the moment, and I am trying to map out a hierachical tree to show people and who they are responsible for. Basically I can user A and user B and they can each be responsible for the same person.
Currently to highlight this in my JSON data that builds the visualisation I am repeating data, is there away to not repeat data and use the same data point when 2 or more people are responsible for the same person?
Here is my JSfiddle example
My Hierachical Visualisation
You will see here that, Raymond Reddington & Donald Ressler have cross over between some of their responsibilites, I am repeating the data which seems inefficient, is there a better way, here is my JSON.
[
{
"name" : "Company Name",
"parent" : null,
"children": [
{
"name" : "Raymond Reddington",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Debe Zuma",
"parent" : "Raymond Reddington",
},
{
"name" : "Tom Keen",
"parent" : "Raymond Reddington",
},
{
"name" : "Aram Mojtabai",
"parent" : "Raymond Reddington",
}
]
},
{
"name" : "Elizabeth Keen",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Samar Navabi",
"parent" : "Elizabeth Keen",
},
{
"name" : "Meera Malik",
"parent" : "Elizabeth Keen",
},
{
"name" : "Mr. Kaplan",
"parent" : "Elizabeth Keen",
},
{
"name" : "Reven Wright",
"parent" : "Elizabeth Keen",
}
]
},
{
"name" : "Donald Ressler",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Matius Solomon",
"parent" : "Donald Ressler",
"size" : 3938
},
{
"name" : "Peter Kotsiopulos",
"parent" : "Donal Ressler",
"size" : 3938
},
{
"name" : "Tom Keen",
"parent" : "Raymond Reddington",
"size" : 3938
},
{
"name" : "Aram Mojtabai",
"parent" : "Raymond Reddington",
"size" : 3938
}
]
},
{
"name" : "Harold Cooper",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Samar Navabi",
"parent" : "Elizabeth Keen",
"size" : 3938
},
{
"name" : "Meera Malik",
"parent" : "Elizabeth Keen",
"size" : 3938
}
]
}
]
}
]
This website details a method of converting flat data to the hierarchical data required by d3 http://www.d3noob.org/2014/01/tree-diagrams-in-d3js_11.html
They explain it well too. As the author notes it is originally based on https://stackoverflow.com/a/17849353/1544886
I have copied and pasted their website's example below:
var data = [
{ "name" : "Level 2: A", "parent":"Top Level" },
{ "name" : "Top Level", "parent":"null" },
{ "name" : "Son of A", "parent":"Level 2: A" },
{ "name" : "Daughter of A", "parent":"Level 2: A" },
{ "name" : "Level 2: B", "parent":"Top Level" }
];
will map to:
var treeData = [
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}
];
via:
var dataMap = data.reduce(function(map, node) {
map[node.name] = node;
return map;
}, {});
var treeData = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
treeData.push(node);
}
});
You could extend that further replacing with Ids and using a second normalised array for the lookup:
[{
"id": 0,
"name": "Cherry Tree Lodge"
},{
"id": 1,
"name": "Tom Keen"
},{
"id": 2,
"name": "Debe Zuma"
}]
Also please note that your json data is not strictly valid, you have extra commas.

Categories

Resources