Calling a Child Inside 2 Levels of Nodes

Print the same child nodes from an object but two levels deep

I'm assuming what you're looking for is a way to loop through all of the offerNames, in which case a simple for loop would suffice. Since your data includes nested arrays and objects, we need two loops, one to iterate through your allOffers array and then a nested for loops to iterate through the offers array inside of your allOffers array

        var data = {
"offersBreakdown": {
"totalAddedOffers": 0,
"totalOffers": 2,
"totalAddedRewards": 0,
"totalRewards": 0,
"totalAddedStreakOffers": 0,
"totalStreakOffers": 0,
"allOffers": [{
"offers": [{
"offerName": "Offer name 1",
"imageUrl": "https://url_path_1.jpg"
}, {
"offerName": "Offer name 2",
"imageUrl": "https://url_path_2.jpg"
}, {
"offerName": "Offer name 3",
"imageUrl": "https://url_path_3.jpg"
}, {
"offerName": "Offer name 4",
"imageUrl": "https://url_path_4.jpg"
}]
}]
}
};
var allOffers = [];
var jsonObjectAllOffers = data.offersBreakdown.allOffers;
for (var i = 0; i < jsonObjectAllOffers.length; i++) {
var offers = jsonObjectAllOffers[i].offers;
for (var j = 0; j < offers.length; j++) {
var objectToAppend = {
"Name": offers[j]["offerName"],
"Img": offers[j]["imageUrl"]
};
allOffers.push(objectToAppend);
}
}
console.log(allOffers);

And now you can use your allOffers variable to loop through with the "forEach" and make into HTML

How do I call data from Firebase nested in multiple child nodes?

To retrieve true and false, try the following:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(userID).child("vouchers");
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

String values = dataSnapshot.child("april19").getValue(String.class);
String boolValues = dataSnapshot.child("march19").getValue(String.class);
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

Here you dataSnapshot is at child vouchers, then you easily access april19 and march19 values without iterating.

Traverse to child nodes and find property(upto n levels)

var isStatusMet = function isStatusMet( data ) {
// If the status is NotMet, we finish immediately
if (data.Status === 'NotMet') return false;
// Since only nodes with ContentItems have a status, we check if the node has children and recursively check if every child has no Status of NotMet
else if (data.hasOwnProperty('ContentItems')) return data.ContentItems.every(isStatusMet);
// We're dealing with a child without Status or Childnodes, so we just return true.
// Since the status in not met and the parent node of this node expects in its 'every' loop that we only return false for nodes that have Status NotMet, this makes the recusion work.
else return true;
};

var met = isStatusMet(response);

console.log(met);

Avoiding children nodes appear at same or upper level of parent level

As I understand that you want to calculate level for given node. I would suggest not to use dict, because you do not need to. You can just add a property level calculate level while setting child. Here are my major modifications:

   internal class Node
{
public Node(){
Level = -1;
Parents = new List<Node>();
}
public List<Node> Parents { get; set; }
private Node m_child;
public Node Child
{
get { return m_child; }
set
{
m_child = value;
value.Parents.Add(this);
m_child.CalculateLevel();
}
}
public int Id { get; set; }
public string Title { get; set; }
public int Level {get; private set;}
public void CalculateLevel(){
if(Parents.Count() == 0){
this.Level = 0;
return;
}
foreach (var parent in this.Parents)
{
parent.CalculateLevel();
}

this.Level = Parents.Select(p => p.Level).Max() + 1;
}
}

Following is full code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace coordinatesGeneration
{
class Program
{
internal class Node
{
public Node(){
Level = -1;
Parents = new List<Node>();
}
public List<Node> Parents { get; set; }
private Node m_child;
public Node Child
{
get { return m_child; }
set
{
m_child = value;
value.Parents.Add(this);
m_child.CalculateLevel();
}
}
public int Id { get; set; }
public string Title { get; set; }
public int Level {get; private set;}
public void CalculateLevel(){
if(Parents.Count() == 0){
this.Level = 0;
return;
}
foreach (var parent in this.Parents)
{
parent.CalculateLevel();
}

this.Level = Parents.Select(p => p.Level).Max() + 1;
}
}

internal class Program1
{
static void Main(string[] args)
{
Node[] nodes = new Node[]
{
new Node() {Id = 0, Title = "Node1"},
new Node() {Id = 1, Title = "Node2"},
new Node() {Id = 2, Title = "Node7"},
new Node() {Id = 3, Title = "Node3"},
new Node() {Id = 4, Title = "Node4"},
new Node() {Id = 5, Title = "Node5"},
new Node() {Id = 6, Title = "Node6"},
new Node() {Id = 7, Title = "Node8"},
new Node() {Id = 8, Title = "Node9"},
new Node() {Id = 9, Title = "Node10"},
new Node() {Id = 10, Title = "Node11"},
new Node() {Id = 11, Title = "Node12"},
new Node() {Id = 12, Title = "Node13"},
new Node() {Id = 13, Title = "Node14"},
new Node() {Id = 14, Title = "Node15"},
new Node() {Id = 15, Title = "Node16"},
new Node() {Id = 16, Title = "Node17"},
new Node() {Id = 17, Title = "Node18"},
new Node() {Id = 18, Title = "Node19"},
new Node() {Id = 19, Title = "Node20"},
new Node() {Id = 20, Title = "Node21"},
new Node() {Id = 21, Title = "Node22"},
new Node() {Id = 22, Title = "Node23"}

};
nodes[0].Child = nodes[3];
nodes[1].Child = nodes[3];
nodes[2].Child = nodes[4];
nodes[2].Child = nodes[5];
nodes[3].Child = nodes[6];
nodes[3].Child = nodes[7];
nodes[3].Child = nodes[8];
nodes[3].Child = nodes[9];
nodes[6].Child = nodes[10];
nodes[2].Child = nodes[11];
nodes[2].Child = nodes[12];
nodes[7].Child = nodes[13];
nodes[8].Child = nodes[14];
nodes[4].Child = nodes[15];
nodes[5].Child = nodes[15];
nodes[7].Child = nodes[15];
nodes[12].Child = nodes[16];
nodes[13].Child = nodes[16];
nodes[13].Child = nodes[17];
nodes[14].Child = nodes[18];
nodes[8].Child = nodes[19];
nodes[13].Child = nodes[20];
nodes[14].Child = nodes[20];
nodes[8].Child = nodes[21];
nodes[15].Child = nodes[21];
nodes[18].Child = nodes[22];
nodes[19].Child = nodes[22];

foreach(var n in nodes){
Console.WriteLine(n.Title + " (Level: " + n.Level + ") > PARENTS: " + (n.Parents.Count() != 0 ? n.Parents.Count() + " ( " + (n.Parents.Count() == 1 ? (n.Parents[0].Title + " @ " + n.Parents[0].Level) : n.Parents.Select(p => p.Title + " @ " + p.Level).Aggregate((c,next) => c + ", " + next)) + ")" : "Root") );
}

}
}
}
}

Above code will produce following output.

Sample Image

So this is how I would calculate level. Please let me know if you need anything else!

NOTE: I have not handled every case. So it would break if you try to set null as child.

You can also just loop around each node and call its CalculateLevel method like after initialisation and do not call while setting Child.

foreach(var n in nodes){
n.CalculateLevel();
}

Hope this helps!

jsTree load children of child elements in ajax call

Based on Livius answer.

           [{"text" : "Child 2", "id" : "2", "children" :[{"text" : "Grand Child 2", "id" : "12"}]}, 
{"text" : "Child 3", "id" : "3", "children" :[{"text" : "Grand Child 3", "id" : "13"}]},
{"text" : "Parent 4", "id" : "4", "children" :[{"text" : "Grand Child 4", "id" : "14"}]},
{"text" : "Child 5", "id" : "5", "children" :[{"text" : "Grand Child 5", "id" : "15"}]}]

It is working when we use the nested children structure not the parent child id structure (Alternative structure as named on jsTree.com).

Working Fiddle

How do I return all children of a tree, given a level?

You have at least four errors:

  1. you are not passing resultArr around, so it cannot accumulate results.
  2. you keep looking at children even after you found that their parent has the searched level - that is a waste of time.
  3. you are making the recursive call with the node's level instead of the level that you are searching for.
  4. your code does not work for first level, because you never check the top node, just its children.

Try this version:

function searchTree(node, level, resultArr)
{
if (node)
{
if (node.level === level)
{
resultArr.push(node);
}
else if (node.children)
{
node.children.forEach((n) => {searchTree(n, level, resultArr);})
}
}
}

You also don't need to store the level in the nodes; you can compute it instead as you do the recursive calls (if you're called with currentLevel, just call your children with currentLevel + 1).

adding childern to tree stucture and print

If you name a method add_child, it should add a child, not children. And if you add children, you should extend the list, not just append the given list on its end.

Working example:

class Node(object):
def __init__(self, value, children=None):
if children is None:
children = []
self.value = value
self.children = children

def __str__(self, level=0):
ret = "\t" * level + repr(self.value) + "\n"
for child in self.children:
ret += child.__str__(level + 1)
return ret

def add_children(self, obj):
self.children.extend(obj)

root = Node('grandmother')
root.children = [Node('daughter'), Node('son')]
root.children[0].children = [Node('granddaughter'), Node('grandson')]
root.children[1].children = [Node('granddaughter'), Node('grandson')]
root.add_children([Node(1), Node(2)])

print(root)

Output:

'grandmother'
'daughter'
'granddaughter'
'grandson'
'son'
'granddaughter'
'grandson'
1
2

Add a node and Find Cost of Path between two given nodes in a Generic Tree with List of Children in C++

A correct implementation of member might look like:

bool tree::member(const Label l, const Tree& t) {
if (isEmpty(t)) return false;
if (t->label == l) return true;
for (childrenList aux = t->children; aux; aux = aux->next) {
if (member(l, aux->child))
return true;
}
return false;
}

The for loop walks the children of the node (eg one level deep), and the recursive member call is responsible for the next level down.

getNode follows the same pattern but returns a Tree:

Tree getNode(const Label & l, const Tree t)
{
if (isEmpty(t)) return emptyTree;
if (t->label == l) return const_cast<Tree>(t);
for (childrenList aux = t->children; aux; aux = aux->next) {
Tree candidate = getNode(l, aux->child);
if (!isEmpty(candidate))
return candidate;
}
return emptyTree;
}

At that point you might as well reimplement member as:

bool tree::member(const Label l, const Tree& t) {
return !isEmpty(getNode(l, t));
}

EDIT: The last branch of addElem is wrong too:

Output tree::addElem(const Label labelOfNodeInTree, const Label labelOfNodeToAdd, const Weight w, Tree& t) {
if ((labelOfNodeInTree == emptyLabel) && isEmpty(t)) {
t = createNode(labelOfNodeToAdd, emptyWeight);
return OK;
}
if (((labelOfNodeInTree == emptyLabel) && !isEmpty(t)) ||
((labelOfNodeInTree != emptyLabel) && isEmpty(t)))
return FAILED;
if (member(labelOfNodeToAdd, t))
return ALREADY_PRESENT;
Tree v = getNode(labelOfNodeInTree, t);
if (v==emptyTree)
return FAILED;
else {
// Get a reference to the first null pointer in the linked list
childrenListElem*& aux = v->children;
while (aux) {
aux = aux->next;
}

// Append a new element by overwriting the pointer
aux = new childrenListElem;
aux->child = createNode(labelOfNodeToAdd, w);
aux->next = nullptr;
return OK;
}
}


Related Topics



Leave a reply



Submit