Determine which children should be displayed in a Kendo treeview based on the field titled "ParentId"

After converting a list of records into JSON format, I am looking to transform this data into a hierarchical KendoTreeView. Here is the JSON data:

[ { "id": 1, "name": "A", "parentID": 0, "hasItems": "true" },
  { "id": 2, "name": "B", "parentID": 1, "hasItems": "false" },
  { "id": 3, "name": "C",  "parentID": 1, "hasItems": "false" },
  { "id": 4, "name": "D",  "parentID": 0, "hasItems": "false" }
]

To achieve this, I want to create a KendoTreeView using the provided JSON data:

<div id="treeview55"></div>

<script>
    dtSrc = new kendo.data.HierarchicalDataSource({
    transport: {
        read: {
            url: "http://localhost:1132/Discontent/GetTreeNodes",
            dataType: "json"
        }
    },
        ,
    schema:{
        model: {
            id: 'id',
            parentId: 'parentID',
            name: 'name'
        }
    }
});

$("#treeview55").kendoTreeView({
    dataSource: dtSrc,
    dataTextField: "name",
    dataValueField: 'id',
});

Result:

    A
    B
    C
    D

Expected Result:

   > A
         B
         C
     D

My question:

Is there a method to generate a KendoTreeView with cascading children and parents based on the provided JSON data in order to achieve the expected result?

Answer №1

Take a look at the snippet of code below to assist in resolving your issue.


     <div id="tree"></div>
   <script>
        var flatData = [ { "id": 1, "text": "A", "parent": 0, "hasItems":                "true" },
 { "id": 2, "text": "B", "parent": 1, "hasItems": "false" },
    { "id": 3, "text": "C",  "parent": 1, "hasItems": "false" },
   { "id": 4, "text": "D",  "parent": 0, "hasItems": "false" }
  ];

  function processTable(data, idField, foreignKey, rootLevel) {
  var hash = {};

 for (var i = 0; i < data.length; i++) {
var item = data[i];
var id = item[idField];
var parentId = item[foreignKey];

hash[id] = hash[id] || [];
hash[parentId] = hash[parentId] || [];

     item.items = hash[id];
    hash[parentId].push(item);
    }

   return hash[rootLevel];
 }

 // Implementing a tree to visualize the data
  $("#tree").kendoTreeView({
 dataSource: processTable(flatData, "id", "parent", 0),
     loadOnDemand: false
   });
  </script>

I've created a sample based on the provided data which may be useful to you.

View the solution on this jsbin link

Answer №2

Currently, the Kendo UI TreeView does not support flat hierarchies like the one provided. It requires data to be structured hierarchically, as demonstrated in this helpful guide from Jon Skeet.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NextJS: Issue: Accessing a client module from a server component is not allowed. The imported name must be passed through instead

My current NextJS setup is structured as shown below: app/page.js 'use client'; import React from 'react'; export default function Home() { return (<div>Testing</div>); } app/layout.js export const metadata = { title ...

JS script for clicking various icons on a webpage that trigger the opening of new tabs

I am working on a webpage where I have 9 icons with the same class. I am trying to write JavaScript code that will automatically open all 9 icons when the webpage loads. I tried using the code below, but it only clicks on the first icon and stops. let ...

implementing nested key property specifications in React

Is it recommended to explicitly set the keys for the children of components when using arrays of Components? I understand that when using arrays of Components the key property is assumed to be the index of the array and should be explicitly set. {arr.ma ...

problems encountered when including next.config.js for sitemap creation in a nextjs application

Just recently, I made an update to my next.config.json file in hopes of boosting SEO performance. However, this change has caused some issues with the next-sitemap module, preventing me from building or starting my app. //next.config.js const withSitemap = ...

Facing issues with receiving API response through Postman encountering error { }

In my MongoDB database, I have created documents for Families, Users, and Devices (https://i.stack.imgur.com/oeDU0.png). My goal is to retrieve all devices associated with a specific family using the family's Id provided in the HTTP request. For examp ...

Storing an image in MongoDB using Multer as a file from Angular is not working as anticipated

I'm currently dealing with an issue that I believe is not functioning correctly. I installed a library in Angular called cropper.js from https://github.com/matheusdavidson/angular-cropperjs. The frontend code provided by the developer utilizes this li ...

Activate the class when clicked

I am facing a minor issue with the JavaScript onClick function. I need a function that will target a specific class, like .modal. Currently, it looks like this <div class="modal" onclick="modalFix()"> <p>here is some text</p> </div> ...

Error encountered in React JS: The property being accessed is undefined and therefore cannot be mapped

I have been working on a MERN project and I am currently at the stage where I am integrating the frontend and backend using Axios. However, I have encountered some issues. One of the most common errors I am facing in my list screens is: TypeError: Cannot r ...

Variations in JSON serialization with loadAll() compared to loadById(Long id)

I have developed a Folder class in Java Spring Boot, which represents the structure of multiple levels of folders for managing bookmarks: @Entity @Setter @Getter @NoArgsConstructor @AllArgsConstructor **public class Folder** implements Serializable { ...

Before being sent, CDATA is eliminated

Currently, I am integrating a SOAP call within an Angular application. One requirement I have is to include CDATA for a specific section of the payload for certain calls. angular.forEach(contactsCollection, function (item, index) { contacts = contact ...

prismjs plugin for highlighting code displays code in a horizontal format

If you're looking for a way to showcase source code on your website with highlighted syntax, prismjs.com may be just what you need. It offers a similar style to monokai... However, I've encountered an issue where the plugin displays my code in a ...

Is it possible for me to overlap a text over hidden text, and if the hidden text becomes visible through JavaScript, my text will shift to the right of the now visible hidden text?

I'm currently working on a website for a company that requires users to complete all the information before proceeding. To achieve this, I created a form with the following code: <form action="Owners Infoback.php" onsubmit="return validateFo ...

Guide to importing multiple controllers using express

For my upcoming full stack project, I am working on various controllers like signup, login, and profile. Instead of manually requiring each controller and adding them to the app using individual lines of code, I am seeking a more efficient solution. I env ...

JavaScript FormData class does not recognize disabled and checked states on Bootstrap 5 switches

I am implementing a Bootstrap 5 switch input that I need to be mandatory, meaning it should be checked by default and not uncheckable. The official documentation suggests combining the attributes checked and disabled. However, it seems like the Javascrip ...

What is the best way to manage horizontal scrolling using buttons?

I was hoping that when the button is clicked, the scroll would move in the direction of the click while holding down the button. Initially, it worked flawlessly, but suddenly it stopped functioning. export default function initCarousel() { const carous ...

Stop users from being able to copy text on their smartphones' internet browsers

I am currently working on creating a competitive typing speed challenge using JavaScript. Participants are required to type all the words they see from a div into a textarea. In order to prevent cheating, such as copying the words directly from the div, o ...

Tips on incorporating the authorization header in the $.post() method with Javascript

When attempting to POST data to the server, I need to include an Authorization header. I attempted to achieve this using: $.ajax({ url : <ServiceURL>, data : JSON.stringify(JSonData), type : 'POST', contentType : "text/html", ...

Challenge of integrating React Router with Express GET requests

I am struggling to understand how react router and express routes work together. This is what I currently have set up: app.get('*', function(req, res) { res.sendFile(path.resolve(__dirname) + '/server/static/index.html'); }); // ...

Using Kotlin to work with JSON strings that contain line breaks and variables

In need of help adding linebreakers to a JSON string for improved readability. val myString = "some string" val myObjectJson = ` { "example1": "value", "example2": $myString }` This will allow me to utilize ...

The issue arises when interfaces are extended by another interface

Is there a way to have classes that implement both the Observer and Comparable interfaces together? interface Comparable<T> { equals: (item: T) => boolean; } interface Observer extends Comparable<Observer> { notify: () => void } ...