将新列表添加到现有java脚本对象

时间:2018-02-24 21:48:19

标签: javascript arrays dataset splice

我正在尝试填充条形图的数据集。我想将'dataset'添加到现有的barData1对象。

但我得到了以下错误。我在这做错了什么?

  

错误:jquery-3.1.1.min.js:2未捕获的TypeError:无法读取属性   'splice'未定义

<script type="text/javascript">
var jsprojStatList = @Html.Raw(ViewBag.projStatList);

    $(document).ready(function () {
        var barData1 = {
            labels: ["No. Of Line Items", "Line Items Ordered", "( % )", "Line Items to be Ordered", "( % )", "PO Generated", "PO Approved", "PO Waiting for Approval"]
        };
        //var obj = JSON.parse(barData1);
        //var parse_obj = JSON.parse(barData1);
        var i = 0;
        for (var key in jsprojStatList) {
            if (jsprojStatList.hasOwnProperty(key)) {
                var val = jsprojStatList[key];
                barData1['datasets'].splice(i, 0, {
                    "label": val.BudgetTypeTitle, "backgroundColor": "rgba(220, 220, 220, 0.5)", "rgba(220, 220, 220, 0.5)": "#fff"
                    , "data": [val.NoOfBudgetItems, val.NoOfBudgetItemsOrdered, val.NoOfBudgetItemsOrderedPercentage, val.NoOfBudgetItemsToBeOrdered
                        , val.NoOfBudgetItemsToBeOrderedPercentage, val.POGenerated, val.POApproved, (val.POGenerated - val.POApproved)]
                });
                i++;
                };
        };
        //}

        var barOptions1 = {
            responsive: true
        };

        var ctx21 = document.getElementById("barChart1").getContext("2d");
        new Chart(ctx21, { type: 'bar', data: barData1, options: barOptions1 
    });
</script>

1 个答案:

答案 0 :(得分:1)

在为其添加值之前,您必须将barData1['datasets']本身定义为数组:

var barData1 = {
    datasets: [], // populated below
    labels: ["No. Of Line Items", "Line Items Ordered", "( % )", "Line Items to be Ordered", "( % )", "PO Generated", "PO Approved", "PO Waiting for Approval"]
};
第一次使用时,

.splice()不会/不能自动为您创建数组。

附注: