使用Jquery Mapping计算多维数组中的唯一元素?

时间:2017-05-16 18:37:26

标签: javascript jquery html5 d3.js chart.js

关于JQuery映射的任何想法都将返回一个重复名称和标题数组及其计数。所以我可以在D3或Chart JS中创建一个条形图(图表JS到目前为止似乎更容易)......

即,我有(例如,使用JSON)

 obj = {"Chocolate":"Organic", "Chocolate":"Fresh", "Chocolate":"Organic", 
    "Vanilla":"Regular", 
    "Vanilla":"Organic","Strawberry":"Fresh","Vanilla":"Regular"}; 

我想要这个

    var data = {
    labels: ["Chocolate", "Strawberry", "Vanilla"],
    datasets: [
        {
            label: "Fresh",
            fillColor: "blue",
            data: [1,0,1] //(1 Fresh chocolate, 1 Fresh Strawberry, No fresh Vanilla)
        },
        {
            label: "Regular",
            fillColor: "red",
            data: [0,0,2] //(0 regular chocolate, 0 regular Strawberry, 2 regular Vanilla)
        },
        {
            label: "Organic",
            fillColor: "green",
            data: [2,1,0] //(2 organic chocolate, 1 organic Vanilla, 0 organic strawberry)
        }
    ]
};

http://jsfiddle.net/u25c7gtj/2/

我尝试了什么?到目前为止,我已经能够通过巧克力,香草或草莓对物品进行分组,但下一步是计算具有匹配属性的物品...我甚至不知道从哪里开始比较它们。我尝试只拉动" Flavor和Type",将它们作为对象进行比较,但比较只产生具有个别风味和类型键和值对的组。

function groupBy(propertyName, array) {
    var groupedElements = {};

    for(var i = 0; i < array.length; i++) {
        var element = array[i];
        var value = element[propertyName];

        var group = groupedElements[value];
        if(group == undefined) {
            group = [element];
            groupedElements[value] = group;
        } else {
            group.push(element);
        }
    }

    return groupedElements;
}

var result = groupBy("flavor", obj)
console.log(result);
$("#results").html(JSON.stringify(result, null, 4));

我也试过下面的代码,似乎只计算总数

 <script type="text/javascript">
 $.ajax({

    url: "/_api/web/lists/getbytitle('Ice Cream List')/items?$select=ID,Flavor,Type",
    type: "GET",
    headers: {
        "accept": "application/json;odata=verbose",
    },
    success: function(data){
       // $.each(data.d.results, function(index, item){
           // console.log(item.Id);
//  console.log(item.Title);
//  console.log(item.m4gs);
 //       });

var  counts = [];

jQuery.each(data.d.results, function(index, item) {
  if (!counts.hasOwnProperty(item)) {
    counts[item] = 1;
  } else {
    counts[item]++;
  }
});
console.log(counts[]);

0 个答案:

没有答案