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

The process of retrieving request data from axios.get and storing it in the Redux store

Recently delving into Redux, I'm curious about how to retrieve request data from a GET method. Upon mounting the component, you can use axios to send a GET request to '/api/v3/products', passing in parameters like pageNumber and pageSize. ...

A streamlined method to verify the presence of a username or email address in MongoDB before registering

I'm currently running a NodeJS server with ExpressJS to manage my /register route. As part of the registration process, I need to confirm that both the user's username and email are unique before allowing them to create an account in the users co ...

Implementing shallow routing with the Next.js 13 framework while having appDir functionality activated

Previously in Next 13 (or with appDir disabled), you could achieve the following: const MyComponent = () => { const router = useRouter(); const toggleStatic = () => { if (router.query.static) { router.push(router.pathname, router.pa ...

Implementing Multiple Identification using JavaScript and PHP

I need to complete a simple task. Here is the code snippet: echo' <div class="col-sm-12" id="recensioni_titolo"> <form role="form" id="review-form" method="post" action="php\insert_comment.php"> ...

unable to successfully npm install canvas

For my GitHub repository, please visit here This project was actively developed until November of last year, after which I did not commit any changes. Today, I attempted to run the project again but encountered the following error. My current system versi ...

In order to display the particle-slider logo effect, the JavaScript on the page needs to be refreshed

I have a website frontend integrated from WordPress using an HTML 5 Blank Child Theme. The site features a logo effect utilizing particle slider for screen sizes greater than 960px, and a flat logo image for screen sizes less than 960px. Everything works p ...

Have you checked the console.log messages?

As a newcomer to web development, I hope you can forgive me if my question sounds a bit naive. I'm curious to know whether it's feasible to capture a value from the browser console and use it as a variable in JavaScript. For instance, when I enco ...

What is the best method for effectively eliminating duplicate objects with the same value from an array?

Let's say we have a collection of jqlite objects, and using the angular.equals function, we can determine if they are equal. How can we utilize this function to eliminate duplicate items from an array of jQlite objects? This is my attempted solution: ...

Sending data when button is clicked from Google Apps Script to sidebar

I have been attempting to pass a list that includes both the start cell and end cell of the active range. I want to then assign each value from this list to separate input fields. document.getElementById("btn-get-range").addEventListener('click&apo ...

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

Is there a way to adjust user privileges within a MenuItem?

One of my tasks is to set a default value based on the previous selection in the Userlevel dropdown. The value will be determined by the Username selected, and I need to dynamically update the default value label accordingly. For example, if "dev_sams" is ...

Exploring the wonders of Node.js, Redis, and Express.js while navigating through the enchanting world of Asynchronous

Hello there, I must confess that this is a whole new realm for me... Here is what we've got: app.get('/user/:user_id/followings', function(req, res) { var response = {} , userId = req.params.user_id , ids = req.param(' ...

Implementing Ideone API functionality on Codeigniter with the use of ajax, javascript, and soapclient

I am new to using Codeigniter and I apologize if my question is basic. I found some code on this site: Working with IDE One API (Full project code available here) and I'm attempting to incorporate it into Codeigniter. I have been able to get it worki ...

What are the steps to creating a unique event within an AngularJs service?

In the midst of my AngularJs project, I find myself faced with a dilemma. I have a service designed to manage button events, but I want another service to handle these events indirectly without directly interacting with the buttons themselves. So, my goal ...

Unable to decode JSON properly within iOS application

Hey there! I've been using NSJSONSerialization to decode JSON data from a web server for my iOS app, and it was working perfectly fine until recently. All of a sudden, the decoding process is only returning null values. I even tried hardcoding the JSO ...

Switch Focus and Collapse Submenus upon Menu Click in Recursive React Menu

I've created a dynamic menu system in React using Material-UI that supports recursion for submenus. I'm aiming to implement the following features: 1. When a menu item is clicked, all other open submenus should close and focus on the clicked men ...

The persistence of postback from the javascript function despite returning false when utilizing Asp Radiobuttonlist

HTML: <asp:RadioButtonList ID="rdStatus" runat="server" Height="48px" RepeatDirection="Horizontal" AutoPostBack="true" OnSelectedIndexChanged="rdStatus_SelectedIndexChanged" CssClass="rad"> ...

JavaScript-Based Header Features Similar to Excel

Currently, I am in the process of developing a function that generates a sequence of strings similar to Excel headers. For those who may not be familiar with Excel, the sequence goes like this: A,B,...,Z,AA,...,AZ,BA,...,ZZ,AAA,...,etc. Here is the code ...

Access the Ajax response and store it in a JavaScript variable

I've successfully created a script that inserts data into an MySQL database using a modal and AJAX. However, I'm having trouble retrieving the response to complete an input field. Below is my current script: $.ajax({ url:"insertar_cl ...

The functionality of JavaScript on an icon that is supposed to expand and collapse a table is not functioning properly when the enter

On this particular page, I have a toggleable table of information that expands and collapses when the user clicks on a clickable +/- icon. However, there seems to be an issue where if the user tabs to the icon and tries to expand/collapse it by pressing en ...