我正在将json对象转换为数组。我得到的数据如下。我尝试使用Google,但找不到答案。如何通过下面的数据解决此问题
[{"january":"0.00","february":"0.00","mac":"1271.00","april":"5.00","may":"0.00","june":"0.00","july":"0.00","august":"0.00","september":"0.00","october":"0.00","november":"0.00","december":"0.00"}]
进入此
$scope.data = [
[0.00, 0.00, 1271.00, 5.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00]
];
在file.html
中<div class="card">
<div class="card-header">
<i class="icon-graph icon-bg"></i>Bar Chart
</div>
<canvas id="bar" class="chart chart-bar" chart-data="graph" chart-labels="labels"></canvas>
</div>
在file.js中
$http.get(commonData.apiURL + 'dashboard/countDataGraph.php')
.success(function (data) {
$scope.graph = data;
console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
答案 0 :(得分:2)
JavaScript中的对象属性是无序的,因此使用Object.values()
的解决方案不能保证生成的数组正确排序。
您必须以正确的顺序获取各个值,并从中构造一个新的数组。预定义一系列的月份,并结合map()
操作将达到目的:
const months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
const data = [{"january":"0.00","february":"0.00","march":"1271.00","april":"5.00","may":"0.00","june":"0.00","july":"0.00","august":"0.00","september":"0.00","october":"0.00","november":"0.00","december":"0.00"}];
const result = data.map(v => months.map(m => v[m]));
console.log(result);
答案 1 :(得分:-1)
您可以使用函数Object.values
Object.values(o) // Returns an array of values.
let obj = [{"january":"0.00","february":"0.00","mac":"1271.00","april":"5.00","may":"0.00","june":"0.00","july":"0.00","august":"0.00","september":"0.00","october":"0.00","november":"0.00","december":"0.00"}];
let values = obj.map(Object.values);
console.log(values);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:-1)
您可以使用map()
和Object.values
const arr = [{"january":"0.00","february":"0.00","mac":"1271.00","april":"5.00","may":"0.00","june":"0.00","july":"0.00","august":"0.00","september":"0.00","october":"0.00","november":"0.00","december":"0.00"}]
const res = arr.map(x => Object.values(x));
console.log(res);