循环通过JSON并将值添加到代码?

时间:2017-05-24 15:29:59

标签: javascript jquery json

我使用PHP将JSON对象返回给Javascript,我想循环遍历该对象,然后在代码中打印每个值。

这是功能:

// Define things a user *has* to be able to do (has to implement)
interface iUser {
    public function set();
    public function get();
    public function setTable();
}

// Define our default abstraction
abstract class DefaultUser implements iUser {
    private $_username = false;
    private $_userid = false;
    protected $_table = false;
    public function get() {
        /* the default implementation */
        echo "defaultUser get";
    }
    public function set() {
        echo "defaultUser set";
    }
}

class UserAdmin extends DefaultUser {
    public function setTable($table) {
        $this->_table = $table;
    }

    public function set() {
        echo "UserAdmin's set() and also my parent's set()";
        parent::set();
    }

    public function get() {
        echo "UserAdmin's get() and also my parent's get()";
        parent::get();
    }
}

class UserCMS extends DefaultUser {
    public function setTable($table) {
        $this->_table = $table;
    }

    public function set() {
        echo "UserCMS's set() and also my parent's set()";
        parent::set();
    }

    public function get() {
        echo "UserCMS's get() and also my parent's get()";
        parent::get();
    }
}

如您所见,标签:[]为空,我需要从JSON数组中提取值并将它们添加到'[]'。

我通过AJAX返回JSON,所以我想我不能使用PHP来遍历对象。

1 个答案:

答案 0 :(得分:1)

下面的代码使用JSON中的labels值填充label数组

var json = [{
                label: 'FiveRP',
                data: [],
                backgroundColor: "rgba(75,192,192,0.4)",
                fill: false,
                lineTension: 0.1,
                borderColor: "rgba(75,192,192,1)",
                borderCapStyle: 'butt'
            }, {
                label: 'GTALife',
                data: [],
                backgroundColor: "rgba(148,0,211,0.4)",
                fill: false,
                lineTension: 0.1,
                borderColor: "rgba(148,0,211,1)",
                borderCapStyle: 'butt'
            }, {
                label: 'GermanV',
                data: [],
                backgroundColor: "rgba(255,165,0,0.4)",
                fill: false,
                lineTension: 0.1,
                borderColor: "rgba(255,165,0,1)",
                borderCapStyle: 'butt'
            }];
            
var arr = [];
for (e of json) {
  arr.push(e.label)
}

var data = {
 labels: arr,
 datasets: json
}
console.log(data.labels);