What is the best method for transforming CakePHP JSON into a format compatible with JS JIT SpaceTree?

I am currently utilizing CakePHP to execute a query on my database table 'Task', which consists of columns like project_id, id, parent_id, title, and description. The code in my controller that handles the query looks like this:

$query= $this->Task->find('threaded', array(
                'conditions' => array(
                    'Task.project_id'  => 83,
                ), 
                'fields' => array(
                    'Task.id',
                    'Task.title',
                    'Task.parent_id',

                )
        ));
//Pass the result to the view
$this->set('query', $query);

When I try to decode the JSON in my view using the following snippet:

<?php echo json_encode($simple); ?>

The resulting JSON structure is as follows:

[
{
    "Task": {
        "id": "475",
        "title": "Have a Picnic",
        "parent_id": "0"
    },
    "children": [
        {
            "Task": {
                "id": "476",
                "title": "Drive/Hike to Mountains",
                "parent_id": "475"
            },
            "children": []
        }
    ]
}

In order for JS JIT SpaceTree to function properly, it requires a different structure, similar to the one shown below:

    {
  "id": "aUniqueIdentifier",
  "name": "usually a nodes name",
  "data": [
      {key:"some key",       value: "some value"},
    {key:"some other key", value: "some other value"}
  ],
  children: [/* other nodes or empty */]
}

However, I am uncertain about how to adjust the current output or modify my query to achieve the required structure. Additionally, I have experimented with both 'threaded' and 'list' find() types but encountered the same structure. Any guidance on this matter would be greatly appreciated!

Answer №1

To organize the results in a desired structure, you can iterate through them and map the data accordingly. This task can be carried out in the controller, view (using a helper), or even in the model by creating a custom find method.

For instance, consider the following basic example. Assuming that data is relevant to your needs and there are no additional fields in the result:

function mapThreaded($source, &$target)
{
    foreach($source as $item)
    {
        $node = array
        (
            'id' => $item['Task']['id'],
            'name' => $item['Task']['title'],
            'children' => array()
        );

        if(count($item['children']))
        {
            mapThreaded($item['children'], $node['children']);
        }

        $target[] = $node;
    }
}

$tasks = $this->Task->find('threaded', array(...));

$tree = array();
mapThreaded($tasks, $tree);

pr($tree);
pr(json_encode($tree, JSON_PRETTY_PRINT)); // requires PHP >= 5.4.0 for pretty print

The output will be a JSON structure similar to this:

[
    {
        "id": "475",
        "name": "Have a Picnic",
        "children": [
            {
                "id": "476",
                "name": "Drive/Hike to Mountains",
                "children": [

                ]
            }
        ]
    }
]

If Spacetree only supports a single root element, you can either use current($tree) or pass the first array entry to Spacetree in JavaScript.

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

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

Leveraging regular expressions for image domains within NextJS next.config.js

Is it possible to use regex in next.config.js to allow image domains? Giphy uses different numbers for its endpoints (e.g. media0.giphy.com, media2.giphy.com), but my regex isn't working and I'm seeing this error message: hostname "media0.gi ...

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

Automatically switch tabs upon pressing/scanning the Return key (using PHP, MySQL, and JavaScript)

Seeking assistance to resolve an ongoing issue that has been troubling me for the past few weeks. I am maintaining a basic web-based database to keep track of product serial numbers leaving our warehouse. The system is secure behind our firewall, so I&apo ...

Execute JavaScript function after the window has finished loading, regardless of any asynchronous downloads

In my app, there is an initialise function that I want to execute only when two conditions are met: first, the window has finished loading ($(window).load()), and second, Typekit has loaded. $(window).load(function() { try { Typekit.load({ act ...

Debounce function fails to properly function when the state is modified within the same function

I've been working on implementing a search-as-you-type feature and I want to debounce the function search that handles API calls. Everything works well when I only call the debounced_search function within the event handler, but I also need to update ...

Understanding and extracting information from a JSON array of objects using the Gson library

I am encountering an issue with gson while attempting to parse a JSON file that contains an array of objects. The error message "Exception in thread "main" com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 2" is being ...

generate a list based on the data inside an array of objects

How can I extract the values from the 'urban' field of type 'gasolina'? { ... "fuelUse" : { "urban" : [ { "value" : 6.2, "unit" : "km/l&qu ...

Issues with displaying or hiding a DIV using javascript - popup box unresponsive

I am working with this ASPX code: <div id="IsAccountingOk" class="modalDialog"> <div> <a href="#close" title="Close" class="close">X</a><br /> <asp:Label ID="lblIsAccountingOkHeader" runat="server" Text ...

Having trouble calling the edit function in React? Keep getting the error message "this.props.onContactSubmit is not a function"? Let's

I am currently experiencing an issue with React. I am trying to edit a contact from the contactList but keep encountering an error: Uncaught TypeError: this.props.handleContactEditSubmit is not a function... var ContactBox = React.createClass({ getInitia ...

HTML - lunar phases - update link based on user interaction

Reason: I am aiming to include tide times on my website as a minor feature rather than the main focus. Objective: As part of this tide times feature, I want to offer users a dropdown menu to choose a location and have the default tide times update based o ...

Retrieve a JSON file with Hebrew data from a server and then interpret it using Node.js

I have a JSON file with dynamic content stored on a remote server acting as an API. The file also includes Hebrew text in its values. How can I retrieve the response and convert it into a JSON object? Here is the code snippet I have put together using Re ...

How can we utilize $interval in Angular without any initial delay?

I have created a function that animates an object on the screen as follows: $interval(function() { $('#cloudLeftToRight').animate({ left: '+=250%', }, 7000, function() { $('#cloudLeftToRight').removeAt ...

Error message: "Sonar detects a need for serialization or making transient"

Having this serializable class implemented as follows: public class Test implements Serializable{ private String id; private Map<String,Object> otherProperties; } Encountering issues with serialization due to the https://i.sstatic.net/6ap67.png ...

Get the @html.dropdownlistfor filtered for me

Currently, I am working on a project that requires me to filter the options in my second dropdown list based on the selection made in the first dropdown list. While the concept is clear, implementing it becomes tricky as I lack expertise in jQuery or JavaS ...

Is there a way to showcase a resultset using async await in JavaScript?

I need help formatting the resultset from my query into a json list. Currently, only the first record is being displayed. How can I use async await to return multiple records? https://i.sstatic.net/rrPPW.png I am looking to achieve this output https://i. ...

Sending requests across domains from HTTPS to HTTP with callback functionality, and reversing the process

Prior to our conversation, I had created it using Flash. I uploaded a special file (crossdomain.xml) on the server side (https), while the Flash component was placed on the http server. Although they belong to different domains on the https and http serv ...

I am unable to reach my pages through their URL directly, I can only access them through links within Next.js

My next JS application runs smoothly during development, but encounters an issue when published online. I can only access the pages through links on the home page that direct to those specific pages. For instance, trying to navigate directly to www.examp ...

I aim to display a success message upon form submission

Can someone assist me with a problem I'm facing? I need to display a success message after successfully submitting a form. I'm utilizing bootstrap and jQuery for this task, along with an email service known as emailJS. This service enables us to ...

Tips on eliminating the "-" symbol from a string using jQuery

Is there a way to eliminate all instances of "-" from a complete string? I currently have a line of code that successfully removes the first "-", but I need it to remove all occurrences. Here's an example image name: cropped-Journal-trend-02.png i ...