在 node.js 中使用 chart.js 显示数组中的两个数据集

我试图从我的数组中显示两个元素,一个作为标签,即“某种作物的名称”,另一个是数据本身,即“作物的数量”,我的问题是我的图表如果相同的作物出现超过它与其数量分开显示的 

http://img4.mukewang.com/612784da0001e06909850460.jpg

在我的 app.js(快速服务器)上


 app.get('/crop', function (req, res) {

    return new Promise(function(resolve, reject){

    db.serialize(function(){

        db.all('SELECT * FROM harvests', function(err, rows){

            if (!err) {

                resolve(rows)

            }else{

                reject(err)

            }

        })

    })

    }).then(function(rows){

        res.json(rows);

    });

});

在 Html 页面上


<canvas id="chart" ></canvas>

在剧本上


 $(document).ready(function(){

    $.ajax({

    url: 'http://localhost:3000/crop',

    type: 'get',

    dataType: 'json'

    }).then(function(rows){


    let labels = rows.map(function(e) {

    return e.keyCrop;

    });

    let data = rows.map(function(e) {

     return e.quantity;

    });


    let ctx = document.getElementById('chart').getContext('2d');

    let myChart = new Chart(ctx, {

    type: 'bar',

    data: {

    labels: labels,

    datasets: [{

    label: 'What Farmers are Growing',

    data: data,

    backgroundColor:

   'rgba(255, 99, 132, 0.2)',

    borderColor:

    'rgba(255, 99, 132, 1)',

    borderWidth: 1

        }]

    }

    });

    });

    })

我希望有一种情况,如果作物相同,它会添加它们的总量并显示在一个名称(标签)上


天涯尽头无女友
浏览 303回答 1
1回答

子衿沉夜

在从行数组中单独取出标签和数据之前,您可以创建一个函数来添加和删除重复项。它将添加重复值,并在您从 AJAX 调用中获得的对象中仅生成一对密钥。const addDuplicate = () => {&nbsp; const rows = [&nbsp; &nbsp; { labels: 'Avocados', data: 100 },&nbsp; &nbsp; { labels: 'Maize', data: 25000 },&nbsp; &nbsp; { labels: 'Tomatoes', data: 50 },&nbsp; &nbsp; { labels: 'Tomatoes', data: 50 },&nbsp; &nbsp; { labels: 'Cabbages', data: 4000 },&nbsp; &nbsp; { labels: 'French Beans', data: 5500 },&nbsp; &nbsp; { labels: 'Avocados', data: 50000 },&nbsp; &nbsp; { labels: 'Avocados', data: 34000 },&nbsp; &nbsp; { labels: 'Tomatoes', data: 50 }&nbsp; ];&nbsp; for (let i = 0; i < rows.length; i++) {&nbsp; &nbsp; for (let j = i + 1; j < rows.length; j++) {&nbsp; &nbsp; &nbsp; if (rows[i].labels === rows[j].labels) {&nbsp; &nbsp; &nbsp; &nbsp; rows[i].data += rows[j].data;&nbsp; &nbsp; &nbsp; &nbsp; rows.splice(j, 1);&nbsp; &nbsp; &nbsp; &nbsp; j--;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; console.log(rows);};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript