0
我有一個Ajax調用,其中即時通訊用戶選擇的顏色,並嘗試將結果堆疊在一個數組中。我試圖堆疊顏色,然後是幾個月。無法將數據拆分成正確的數組
這裏是我的代碼至今:
var yr = element.created_date.slice(0, 4);
var month = parseInt(element.created_date.slice(5,7));
var color = element.colorvalue.split(",");
if (counts[color] === undefined) {
counts[color] = {};
}
if (counts[color][yr] === undefined) {
counts[color][yr] = {};
}
current_value = counts[color][yr][month];
if (current_value === undefined) {
// Doesnt exist yet, so add it
counts[color][yr][month] = 1;
} else {
// Exists, so increment by 1
counts[color][yr][month] = current_value + 1;
}
});
這是輸出IM從此獲得:
{"red, blue, yellow":{"2015":{"8":1}},"blue, red":{"2015":{"8":1}},"red":{"2015":{"7":1,"8":2}},"yellow":{"2015":{"10":1}},"blue":{"2015":{"9":1}},"yellow, red, blue":{"2015":{"7":1}}}
我使用.split( 「」),認爲它會理解把顏色分成自己的堆棧,但事實並非如此。這就是我期待的迴歸。
{"red":{"2015":{"1":23,"2":19,"3":32,"4":18,"5":12,"6":22,"7":23,"8":21,"9":16,"10":23,"11":22,"12":14},"2016":{"1":19,"2":9}},"yellow":{"2015":{"9":1,"12":1},"2016":{"1":16,"2":3}},"blue":{"2015":{"11":1,"12":2},"2016":{"1":5,"2":1}}}
這裏是一個jsfiddle來展示我試圖完成什麼樣的例子。有人會知道我錯過了什麼嗎? https://jsfiddle.net/awo5aaqb/29/
哪來的的jsfiddle? – roullie
我在這裏很糟糕,它是https://jsfiddle.net/awo5aaqb/29/ –
.split()返回一個數組,你應該遍歷該數組以獲得每種顏色。 – ijball