AngularJS - Json to Tree structure - javascript

I 've seen lots of answers that turn a Json response to a Ul Tree structure.
The thing is that all these subjects where around a nested response pointing
out the relationship between parent object and child object.
I have a non nested Json response indicating the relation by reference to the objects property.
The following is part of the response:
{"id":"1","parent_id":null,"name":"Item-0"},
{"id":"2","parent_id":"1","name":"Item-1"},
{"id":"3","parent_id":"2","name":"Item-2"},
{"id":"4","parent_id":"2","name":"Item-4"},
{"id":"5","parent_id":"2","name":"Item-5"},
{"id":"6","parent_id":"2","name":"Item-6"},
{"id":"7","parent_id":"2","name":"Item-7"},
{"id":"8","parent_id":"2","name":"Item-8"},
{"id":"9","parent_id":"2","name":"Item-9"},
{"id":"10","parent_id":"1","name":"Item-3"},
{"id":"11","parent_id":"10","name":"Item-10"},
You might already noticed that the each object conects with his father through the parent_id which is conected to his parent's id.
I tried to create a custom directive to read the response and through recursion to build the Tree structure.
Till now I succeeded to only create the first level of the tree.
Demo
app.directive('tree',function(){
var treeStructure = {
restrict: "E",
transclude: true,
root:{
response : "=src",
Parent : "=parent"
},
link: function(scope, element, attrs){
var log = [];
scope.recursion = "";
angular.forEach(scope.response, function(value, key) {
if(value.parent_id == scope.Parent){
this.push(value);
}
}, log);
scope.filteredItems = log;
scope.getLength = function (id){
var test = [];
angular.forEach(scope.response, function(value, key) {
if(value.parent_id == id){
this.push(value);
}
}, test);
if(test.length > 0){
scope.recursion = '<tree src="scope.response" parent="'+id+'"></tree>';
}
return scope.recursion;
};
},
template:
'<ul>'
+'<li ng-repeat="item in filteredItems">'
+'{{item.name}}<br />'
+'{{getLength(item.id)}}'
+'</li>'
+'<ul>'
};
return treeStructure;
});
app.controller('jManajer', function($scope){
$scope.information = {
legend : "Angular controlled JSon response",
};
$scope.response = [
{"id":"1","parent_id":null,"name":"Item-0"},
{"id":"2","parent_id":"1","name":"Item-1"},
{"id":"3","parent_id":"2","name":"Item-3"},
{"id":"4","parent_id":"2","name":"Item-4"},
{"id":"5","parent_id":"2","name":"Item-5"},
{"id":"6","parent_id":"2","name":"Item-6"},
{"id":"7","parent_id":"2","name":"Item-7"},
{"id":"8","parent_id":"2","name":"Item-8"},
{"id":"9","parent_id":"2","name":"Item-9"},
{"id":"10","parent_id":"1","name":"Item-2"},
{"id":"11","parent_id":"10","name":"Item-10"},
];
});
Is there any one who could show me how to convert this kind of array to Tree structure through recursion?

Transform your array first recursive in a nested one
var myApp = angular.module('myApp', []);
myApp.controller('jManajer', function($scope) {
$scope.res = [];
$scope.response = [{
"id": "1",
"parent_id": 0,
"name": "Item-0"
}, {
"id": "2",
"parent_id": "1",
"name": "Item-1"
}, {
"id": "3",
"parent_id": "2",
"name": "Item-3"
}, {
"id": "4",
"parent_id": "2",
"name": "Item-4"
}, {
"id": "5",
"parent_id": "2",
"name": "Item-5"
}, {
"id": "6",
"parent_id": "2",
"name": "Item-6"
}, {
"id": "7",
"parent_id": "2",
"name": "Item-7"
}, {
"id": "8",
"parent_id": "2",
"name": "Item-8"
}, {
"id": "9",
"parent_id": "2",
"name": "Item-9"
}, {
"id": "10",
"parent_id": "1",
"name": "Item-2"
}, {
"id": "11",
"parent_id": "10",
"name": "Item-10"
}, ];
function getNestedChildren(arr, parent) {
var out = []
for (var i in arr) {
if (arr[i].parent_id == parent) {
var children = getNestedChildren(arr, arr[i].id)
if (children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out
}
$scope.res = getNestedChildren($scope.response, "0");
console.log($scope.res);
$scope.nested_array_stingified = JSON.stringify($scope.res);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.angularjs.org/1.3.11/angular.js"></script>
</head>
<body ng-app="myApp" ng-controller="jManajer">
{{nested_array_stingified}}
</body>
</html>
After that you can follow the tutorial here for example http://sporto.github.io/blog/2013/06/24/nested-recursive-directives-in-angular/

You need to unflatten your data before passing it to your view.
I have modified your code a bit, also I have transformed your data and replaced the depth and relational fields with integers, it's more easy to compare integers rather than comparing strings and null values.
In this example I have used Undescore.js' powerful functions in order to unflatten the array.
The code can be found as a helper function inside your directive:
unflatten = function (array, parent, tree) {
tree = typeof tree !== 'undefined' ? tree : [];
parent = typeof parent !== 'undefined' ? parent : {
id: "0"
};
var children = _.filter(array, function (child) {
return child.parent_id == parent.id;
});
if (!_.isEmpty(children)) {
if (parent.id == "0" || parent.id == null) {
tree = children;
} else {
parent['children'] = children
}
_.each(children, function (child) {
unflatten(array, child)
});
}
console.log(tree)
return tree;
}
If you want a VanillaJs solution check out this piece of code
Also here is a demo simulating an interactive tree with your data
The underscore unflatten function was taken from here .

Related

How to update a specific node of a tree structured global json object in javascript?

I passed a global tree structured JSON string in jquery fancy tree. I can add a new node data to the global object. I am not able to update a specific node of the global JSON string although I can find that specific node.
I have tried the following way of doing what I wanted but at the end the global variable is not changed. I also tried recursive way but not worked too. Also this is my first question at stackoverflow. I simplified the data because real data is so big.
// global json object array
var treeViewData = [
{
"nodeData": {
"physicalid": "A",
"rootToNode": "A-0",
"level": "0",
"attribute": "English-english"
},
"children": [
{
"nodeData": {
"physicalid": "B",
"rootToNode": "A-0:B-1",
"level": "1",
"attribute": "Finish-finish"
},
"children": []
},
{
"nodeData": {
"physicalid": "C",
"rootToNode": "A-0:C-1",
"level": "1",
"attribute": "Arabic-arabic"
},
"children": [
{
"nodeData": {
"physicalid": "D",
"rootToNode": "A-0:C-1:D-2",
"level": "2",
"attribute": "Spanish-spanished"
},
"children": []
}
]
}
]
}
]
Here is the update method. rootToNode is unique.
findAndUpdateNodeIterative: function(selfNodeRootPath, updatedNode) {
console.log("+++++++++ findAndUpdateNodeIterative ++++++++");
var thisContext = this;
var currentNode = thisContext.treeViewData[0];
var i, currentChild, result;
var flag = true;
while (flag) {
if (currentNode.nodeData.rootToNode === selfNodeRootPath) {
currentNode.nodeData.attribute = updatedNode.nodeData.attribute;
flag = false;
} else {
let it = true;
for (i = 0; i < currentNode.children.length && it; i += 1) {
currentChild = currentNode.children[i];
var currentNodeLevel = parseInt(currentChild.nodeData.level);
var targetPhysicalId = selfNodeRootPath.split(':')[currentNodeLevel].split("-")[0];
if (targetPhysicalId === currentChild.nodeData.physicalid) {
// Search in the current child
currentNode = currentChild;
it = false;
}
}
}
}
console.log("---------- findAndUpdateNodeIterative ---------");
},
usage
var updatedNode = {
"nodeData": {
"physicalid": "D",
"rootToNode": "A-0:C-1:D-2",
"level": "2",
"attribute": "Spanish-spanish"
},
"children": []
};
thisContext.findAndUpdateNodeIterative(updatedNode.nodeData.rootToNode, updatedNode);
console.log(thisContext.treeViewData); // **not updated**
RequireJS Code structure,
// about 4000 lines are present in this module
define("CustomModule", ["fewModules"], function(fewModules) {
var widget = {
init: function() {
this.treeViewData = '';
},
// many methods are here
update: function() {
var thisContext = this;
// rest api call brings the data nodesMap
for (let selectedObject of nodesMap.values()) {
// many lines
thisContext.findAndUpdateNodeIterative(updatedNode.nodeData.rootToNode, updatedNode);
console.log(thisContext.treeViewData); // not updated treeViewData
}
}
};
return widget;
}

Reverse Traverse a hierarchy

I have a hierarchy of objects that contain the parent ID on them. I am adding the parentId to the child object as I parse the json object like this.
public static fromJson(json: any): Ancestry | Ancestry[] {
if (Array.isArray(json)) {
return json.map(Ancestry.fromJson) as Ancestry[];
}
const result = new Ancestry();
const { parents } = json;
parents.forEach(parent => {
parent.parentId = json.id;
});
json.parents = Parent.fromJson(parents);
Object.assign(result, json);
return result;
}
Any thoughts on how to pull out the ancestors if I have a grandchild.id?
The data is on mockaroo curl (Ancestries.json)
As an example, with the following json and a grandchild.id = 5, I would create and array with the follow IDs
['5', '0723', '133', '1']
[{
"id": "1",
"name": "Deer, spotted",
"parents": [
{
"id": "133",
"name": "Jaime Coldrick",
"children": [
{
"id": "0723",
"name": "Ardys Kurten",
"grandchildren": [
{
"id": "384",
"name": "Madelle Bauman"
},
{
"id": "0576",
"name": "Pincas Maas"
},
{
"id": "5",
"name": "Corrie Beacock"
}
]
},
There is perhaps very many ways to solve this, but in my opinion the easiest way is to simply do a search in the data structure and store the IDs in inverse order of when you find them. This way the output is what you are after.
You could also just reverse the ordering of a different approach.
I would like to note that the json-structure is a bit weird. I would have expected it to simply have nested children arrays, and not have them renamed parent, children, and grandchildren.
let data = [{
"id": "1",
"name": "Deer, spotted",
"parents": [
{
"id": "133",
"name": "Jaime Coldrick",
"children": [
{
"id": "0723",
"name": "Ardys Kurten",
"grandchildren": [
{
"id": "384",
"name": "Madelle Bauman"
},
{
"id": "0576",
"name": "Pincas Maas"
},
{
"id": "5",
"name": "Corrie Beacock"
}
]
}]
}]
}]
const expectedResults = ['5', '0723', '133', '1']
function traverseInverseResults(inputId, childArray) {
if(!childArray){ return }
for (const parent of childArray) {
if(parent.id === inputId){
return [parent.id]
} else {
let res = traverseInverseResults(inputId, parent.parents || parent.children || parent.grandchildren) // This part is a bit hacky, simply to accommodate the strange JSON structure.
if(res) {
res.push(parent.id)
return res
}
}
}
return
}
let result = traverseInverseResults('5', data)
console.log('results', result)
console.log('Got expected results?', expectedResults.length === result.length && expectedResults.every(function(value, index) { return value === result[index]}))

How to delete object from an array of objects having relations with each arrays?

This Object have relationship as: childOne > childTwo > childThree > childFour > childFive > childSix.
{
"parentObj": {
"childOne": [
{
"name": "A",
"id": "1"
},
{
"name": "B",
"id": "2"
}
],
"childTwo": [
{
"name": "AB",
"parent_id": "1",
"id": "11"
},
{
"name": "DE",
"parent_id": "2",
"id": "22"
}
],
"childThree": [
{
"name": "ABC",
"parent_id": "22",
"id": "111"
},
{
"name": "DEF",
"parent_id": "11",
"id": "222"
}
],
"childFour": [
{
"name": "ABCD",
"parent_id": "111",
"id": "1111"
},
{
"name": "PQRS",
"parent_id": "111",
"id": "2222"
}
],
"childFive": [
{
"name": "FGRGF",
"parent_id": "1111",
"id": "11111"
},
{
"name": "ASLNJ",
"parent_id": "1111",
"id": "22222"
},
{
"name": "ASKJA",
"parent_id": "1111",
"id": "33333"
}
],
"childSix": [
{
"name": "SDKJBS",
"parent_id": "11111",
"id": "111111"
},
{
"name": "ASKLJB",
"parent_id": "11111",
"id": "222222"
}
]
}
}
Is there any way to delete an item by ID and the objects which are associated with that particular ID should get deleted(i.e., If I do delete parentObj.childTwo[1], then all the related object beneath it should also gets deleted).
Looping manually is too bad code, and generate bugs. There must be better ways of dealing with this kind of problems like recursion, or other.
The data structure does not allow for efficient manipulation:
By nature objects have an non-ordered set of properties, so there is no guarantee that iterating the properties of parentObj will give you the order childOne, childTwo, childThree, ... In practice this order is determined by the order in which these properties were created, but there is no documented guarantee for that. So one might find children before parents and vice versa.
Although the id values within one such child array are supposed to be unique, this object structure does not guarantee that. Moreover, given a certain id value, it is not possible to find the corresponding object in constant time.
Given this structure, it seems best to first add a hash to solve the above mentioned disadvantages. An object for knowing a node's group (by id) and an object to know which is the next level's group name, can help out for that.
The above two tasks can be executed in O(n) time, where n is the number of nodes.
Here is the ES5-compatible code (since you mentioned in comments not to have ES6 support). It provides one example call where node with id "1111" is removed from your example data, and prints the resulting object.
function removeSubTree(data, id) {
var groupOf = {}, groupAfter = {}, group, parents, keep = { false: [], true: [] };
// Provide link to group per node ID
for (group in data) {
data[group].forEach(function (node) {
groupOf[node.id] = group;
});
}
// Create ordered sequence of groups, since object properties are not ordered
for (group in data) {
if (!data[group].length || !data[group][0].parent_id) continue;
groupAfter[groupOf[data[group][0].parent_id]] = group;
}
// Check if given id exists:
group = groupOf[id];
if (!group) return; // Nothing to do
// Maintain list of nodes to keep and not to keep within the group
data[group].forEach(function (node) {
keep[node.id !== id].push(node);
});
while (keep.false.length) { // While there is something to delete
data[group] = keep.true; // Delete the nodes from the group
if (!keep.true.length) delete data[group]; // Delete the group if empty
// Collect the ids of the removed nodes
parents = {};
keep.false.forEach(function (node) {
parents[node.id] = true;
});
group = groupAfter[group]; // Go to next group
if (!group) break; // No more groups
// Determine what to keep/remove in that group
keep = { false: [], true: [] };
data[group].forEach(function (node) {
keep[!parents[node.parent_id]].push(node);
});
}
}
var tree = {"parentObj": {"childOne": [{"name": "A","id": "1"},{"name": "B","id": "2"}],"childTwo": [{"name": "AB","parent_id": "1","id": "11"},{"name": "DE","parent_id": "2","id": "22"}],"childThree": [{"name": "ABC","parent_id": "22","id": "111"},{"name": "DEF","parent_id": "11","id": "222"}],"childFour": [{"name": "ABCD","parent_id": "111","id": "1111"},{"name": "PQRS","parent_id": "111","id": "2222"}],"childFive": [{"name": "FGRGF","parent_id": "1111","id": "11111"},{"name": "ASLNJ","parent_id": "1111","id": "22222"},{"name": "ASKJA","parent_id": "1111","id": "33333"}],"childSix": [{"name": "SDKJBS","parent_id": "11111","id": "111111"},{"name": "ASKLJB","parent_id": "11111","id": "222222"}]}}
removeSubTree(tree.parentObj, "1111");
console.log(tree.parentObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sure, the function you use to delete an entry should FIRST recurse, which means run itself on the linked entry, unless there is none. So, in psuedocode
function del(name, index)
{
if parent[name][index] has reference
Then del(reference name, reference ID)
Now del parent[name][index]
}
No loop needed.
And since we stop if there is no reference, we do not recurse forever.
Not sure what it is you want but maybe this will work:
const someObject = {
"parentObj": {
"childOne": [
{
"name": "A",
"id": "1"
},
{
"name": "B",
"id": "2"
}
],
"childTwo": [
{
"name": "AB",
"childOne": "1",
"id": "11"
},
{
"name": "DE",
"childOne": "2",
"id": "22"
}
]
}
};
const removeByID = (key,id,parent) =>
Object.keys(parent).reduce(
(o,k)=>{
o[k]=parent[k].filter(
item=>
!(Object.keys(item).includes(key)&&item[key]===id)
);
return o;
},
{}
);
const withoutID = Object.assign(
{},
someObject,
{ parentObj : removeByID("childOne","1",someObject.parentObj) }
);
console.log(`notice that childTwo item with childOne:"1" is gone`);
console.log("without key:",JSON.stringify(withoutID,undefined,2));
const otherExample = Object.assign(
{},
someObject,
{ parentObj : removeByID("childOne","2",someObject.parentObj) }
);
console.log(`notice that childTwo item with childOne:"2" is gone`);
console.log("without key:",JSON.stringify(otherExample,undefined,2));
const both = Object.assign(
{},
someObject,
{ parentObj : removeByID("childOne","1",otherExample.parentObj) }
);
console.log(`notice that childTwo items with childOne are both gone`);
console.log("without key:",JSON.stringify(both,undefined,2));

Rename json keys iterative

I got a very simple json but in each block I got something like this.
var json = {
"name": "blabla"
"Children": [{
"name": "something"
"Children": [{ ..... }]
}
And so on. I don't know how many children there are inside each children recursively.
var keys = Object.keys(json);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
var value = json[key];
delete json[key];
key = key.replace("Children", "children");
json[key] = value;
}
And now I want to replace all "Children" keys with lowercase "children". The following code only works for the first depth. How can I do this recursively?
It looks the input structure is pretty well-defined, so you could simply create a recursive function like this:
function transform(node) {
return {
name: node.name,
children: node.Children.map(transform)
};
}
var json = {
"name": "a",
"Children": [{
"name": "b",
"Children": [{
"name": "c",
"Children": []
}, {
"name": "d",
"Children": []
}]
}, {
"name": "e",
"Children": []
}]
};
console.log(transform(json));
A possible solution:
var s = JSON.stringify(json);
var t = s.replace(/"Children"/g, '"children"');
var newJson = JSON.parse(t);
Pros: This solution is very simple, being just three lines.
Cons: There is a potential unwanted side-effect, consider:
var json = {
"name": "blabla",
"Children": [{
"name": "something",
"Children": [{ ..... }]
}],
"favouriteWords": ["Children","Pets","Cakes"]
}
The solution replaces all instances of "Children", so the entry in the favouriteWords array would also be replaced, despite not being a property name. If there is no chance of the word appearing anywhere else other than as the property name, then this is not an issue, but worth raising just in case.
Here is a function that can do it recursivly:
function convertKey(obj) {
for (objKey in obj)
{
if (Array.isArray(obj[objKey])) {
convertKey[objKey].forEach(x => {
convertKey(x);
});
}
if (objKey === "Children") {
obj.children = obj.Children;
delete obj.Children;
}
}
}
And here is a more generic way for doing this:
function convertKey(obj, oldKey, newKey) {
for (objKey in obj)
{
if (Array.isArray(obj[objKey])) {
obj[objKey].forEach(objInArr => {
convertKey(objInArr);
});
}
if (objKey === oldKey) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
}
}
}
convertKey(json, "Children", "children");
Both the accepted answer, and #Tamas answer have slight issues.
With #Bardy's answer like he points out, there is the issue if any of your values's had the word Children it would cause problems.
With #Tamas, one issue is that any other properties apart from name & children get dropped. Also it assumes a Children property. And what if the children property is already children and not Children.
Using a slightly modified version of #Tamas, this should avoid the pitfalls.
function transform(node) {
if (node.Children) node.children = node.Children;
if (node.children) node.children = node.children.map(transform);
delete node.Children;
return node;
}
var json = {
"name": "a",
"Children": [{
"age": 13,
"name": "b",
"Children": [{
"name": "Mr Bob Chilren",
"Children": []
}, {
"name": "d",
"age": 33, //other props keep
"children": [{
"name": "already lowecased",
"age": 44,
"Children": [{
"name": "now back to upercased",
"age": 99
}]
}] //what if were alrady lowercased?
}]
}, {
"name": "e",
//"Children": [] //what if we have no children
}]
};
console.log(transform(json));

Javascript flatten deep nested children

I really can't figure out this one. I'm trying to flatten the category_id that are deep child of a specific node.
var categories = [{
"category_id": "66",
"parent_id": "59"
}, {
"category_id": "68",
"parent_id": "67",
}, {
"category_id": "69",
"parent_id": "59"
}, {
"category_id": "59",
"parent_id": "0",
}, {
"category_id": "67",
"parent_id": "66"
}, {
"category_id": "69",
"parent_id": "59"
}];
Or visually:
The closest I got to was to recursively loop through the first item found:
function children(category) {
var children = [];
var getChild = function(curr_id) {
// how can I handle all of the cats, and not only the first one?
return _.first(_.filter(categories, {
'parent_id': String(curr_id)
}));
};
var curr = category.category_id;
while (getChild(curr)) {
var child = getChild(curr).category_id;
children.push(child);
curr = child;
}
return children;
}
Current output of children(59) is ['66', '67', '68'].
Expected output is ['66', '67', '68', '69']
I didn't test but it should work:
function getChildren(id, categories) {
var children = [];
_.filter(categories, function(c) {
return c["parent_id"] === id;
}).forEach(function(c) {
children.push(c);
children = children.concat(getChildren(c.category_id, categories));
})
return children;
}
I am using lodash.
Edit: I tested it and now it should work. See the plunker: https://plnkr.co/edit/pmENXRl0yoNnTczfbEnT?p=preview
Here is a small optimisation you can make by discarding the filtered categories.
function getChildren(id, categories) {
var children = [];
var notMatching = [];
_.filter(categories, function(c) {
if(c["parent_id"] === id)
return true;
else
notMatching.push(c);
}).forEach(function(c) {
children.push(c);
children = children.concat(getChildren(c.category_id, notMatching));
})
return children;
}

Categories

Resources