我如何迭代我的多维JSON对象

时间:2018-11-02 03:16:44

标签: javascript php json

我正在使用Google Charts开发PHP和JavaScript,并且我想使用JSON传达图表选项,列和行,而且我不知道如何才能以最佳方式正确地进行操作,因为我做了很多尝试

这是我的PHP代码:

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);
}

这是我的JavaScript代码:

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]
            ]);
            **/
        });
    }
});

我的问题是如何使用JavaScript / JSON变量添加此功能

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

2 个答案:

答案 0 :(得分:0)

在“ feedback”参数中,您应该拥有整个JSON对象,其中包含单个键“ pageSpeed”。第一步是获取关联的对象:

const tableData = feedback.pageSpeed;

现在,您要添加列。因此,对于字典中的每个条目,您都必须使用键和字典条目的值作为参数来调用addColumn():

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

对于值也可以做到这一点,但是可以通过映射键来实现:

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

重要的是要注意,在JavaScript(以及许多语言)中,依靠外部对象的顺序并不是一个好主意。订单应使用数组而不是字典来设置,例如

// 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])));

答案 1 :(得分:0)

只需遍历对象并添加tr td ...您将需要使用

let outputHTML = "<table>";

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

outputHTML += "</table>"

在代码末尾添加此代码以将其发送到dom ...

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