简体   繁体   中英

How can i iterate my multidimentional JSON Object

I'm working on a PHP and JavaScript using Google Charts and i want to communicate charts options, columns and rows using JSON, and i don't know how can i do it correctly in the best way since i tried a lot.

This is my PHP Code :

public function charts()
{
    $this->charts['pageSpeed'] = array(
        'columns' => array('string' => 'Browser', 'number' => 'range'),
        'rows' => array('JS' => 10, 'Images' => 30, 'HTML' => 20, 'CSS' => 30, 'Other' => 10),
        'options' => array(
            'pieHole' => 0.4,
            'width' => 100,
            'height' => 100,
            'legend' => false,
        ) 
    );

    echo json_encode($this->charts);
}

And this my JavaScript Code :

google.charts.load('current', {packages: ['corechart']}).then(function()
{
    if ($('#charts').length)
    {
        data = new google.visualization.DataTable();
        url = window.location.href + '/charts';

        $.getJSON(url, params = null, function(feedback)
        {
            // i want to add rows, here like that
            /**
            data.addColumn('string','Browser');
            data.addColumn('number','range');
            data.addRows([
                ["Javascript",10],
                ["Images",30],
                ["HTML",20],
                ["CSS",30],
                ["Other",10]
            ]);
            **/
        });
    }
});

My Question is how can i add this functions, using JavaScript / JSON variables

data.addColumn('number','range');
data.addRows([
    ["Javascript",10],
    ["Images",30],
    ["HTML",20],
    ["CSS",30],
    ["Other",10]
]);

in your "feedback" parameter, you should have your whole JSON object, which contains a single key, "pageSpeed". Your first step would be to get the associated object:

const tableData = feedback.pageSpeed;

Now, you want to add columns. So, for each entry in the dictionary, you will have to call addColumn() with the key and the value of the dictionary entry as arguments:

Object.keys(tableData.columns).forEach((key) => {
    data.addColumn(key, tableData.columns[key]);
});

The same can also be done with values, but by mapping the keys:

data.addRows(Object.keys(tableData.rows).map((key, i, arr) => [key, arr[key]]))

It is important to note that relying on order on an external object is not a good idea in JavaScript (and in many languages). Order should be set with an array instead of a dictionary, such as

// PHP

[
    "columns" => [ // This key will store the definition of each column
        ["key" => "string", "label" => "Browser"],
        ["key" => "number", "label" => "Range"]
    ],
    "rows" => [ // This looks more like a standardized model instead of random key-value pairs
        ["string" => "JS",     "number" => 10],
        ["string" => "Images", "number" => 30],
        ["string" => "HTML",   "number" => 20],
        ["string" => "CSS",    "number" => 30],
        ["string" => "Other",  "number" => 10]
    ]
]


// JavaScript

const columnKeys = tableData.columns.map(({ key, label }) => {
    data.addColumn(key, label); // ("string", "Browser") for the first iteration, then ("number", "range")
    return key; // the "columnKeys" variable will then look like ["string", "number"]
});

// Here, the rows will be formatted in a way that only the values will be returned, ordered by the column keys order
data.addRows(tableData.rows.map((row) => columnKeys.map((key) => row[key])));

Just iterate over the object and add in tr td...you will need to use something like

let outputHTML = "<table>";

for(d of data) {
    outputHTML += "<tr>"
    outputHTML += "<td>" + d[0] + "</td>"
    outputHTML += "<td>" + d[1] + "</td>"
    outputHTML += "</tr>"
}

outputHTML += "</table>"

at the end of your code add this to send it to dom...

$('.outputDiv').append(outputHtml)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM