簡體   English   中英

如何在JavaScript中將鍵值對對象數組轉換為關聯數組

[英]How can I convert an array of key value pair objects into an associative array in javascript

你們永遠不會讓我失望,我在這個問題上處於一個緊要關頭,我需要在將Java映射轉換為JSON對象時保持其順序,我意識到這幾乎是不可能的,因此我決定使用JSON數組。 但是,對我的特定數據起作用的唯一方法是使用JSON對象的JSON數組。 所以看起來像這樣:

[{"2014-11-18":0},{"2014-11-19":0},{"2014-11-20":0},{"2014-11-21":0},{"2014-11-22":0},{"2014-11-23":0},{"2014-11-24":0}]

使我在這里的代碼:

public static JSONArray dataGenerationDay(ArrayList<String> comp, int days) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("MM-dd-yyyy");
    Map<LocalDate, Integer> compMap = new TreeMap<LocalDate, Integer>();
    JSONArray orderedJSON = new JSONArray();

    //create map of data with date and count
    for (String date : comp) {
        DateTime dt = formatter.parseDateTime(date);
        LocalDate dateTime = new LocalDate(dt);
        if (!compMap.containsKey(dateTime)) {
            compMap.put(dateTime, 1);
        } else {
            int count = compMap.get(dateTime) + 1;
            compMap.put(dateTime, count);
        }
    }


    //if there were days missing in the DB create those days and put them in the map
    //with a zero count
    if (compMap.size() < days){
        LocalDate today = LocalDate.now();
        for (int i = 0; i < days; i++){
            LocalDate dayCount = today.minusDays(days- i);
            if (!compMap.containsKey(dayCount)) {
                compMap.put(dayCount, 0);
            }

        }
    }   

    //json object does not hold order of tree map, create json array
    //of ?json objects? to maintain order for the graph
    for (Map.Entry<LocalDate,Integer> entry : compMap.entrySet()){
        JSONObject object = new JSONObject();
        object.put("" + entry.getKey(), entry.getValue());
        orderedJSON.put(object);
        //test the order of the map for validity
        System.out.println("Key Value Pair Is: " + entry.getKey() + " : " + entry.getValue());
    }
    //test the order of the array for validity
    System.out.println("Ordered JSON List: " + orderedJSON.toString());
    return orderedJSON;
}

希望我的代碼達到標准,試圖保持其盡可能整潔??? 但是回到問題。 這很好用,但是我遇到的問題是將對象數組轉換為javascript中的關聯數組,以便可以將其用於D3js條形圖,這是我愚蠢地嘗試但失敗的代碼

var dateToArray = function(json_object) {

    var dayArray = [];
    for (key in json_object){
        dayArray.push({
            "Date" : key[0],
            "Count" : json_object[key[1]]
        });
    }
    console.log("Here is su array" + dayArray);
    return dayArray;
};

有任何想法嗎?

嘗試這個

var dateToArray = function(json_object) {

    var dayArray = [],
        key;

    for (var i = 0; i < json_object.length; i++) {
        key = Object.keys(json_object[i])[0];

        dayArray.push({
            "Date" : key,
            "Count" : json_object[i][key]
        });
    }

    return dayArray;
};

json_object是數組而不是對象,因此您不應使用for(.. in ..)(for(.. in ..)語句遍歷對象的可枚舉屬性)。 在我的示例中,我使用Object.keys返回對象中的鍵數組,並且可以在Object中通過鍵獲取值,因為在JS中,從對象獲取屬性的方法有兩種,例如obj.key或obj [key]。

演示: http//jsbin.com/ruse​​ja/1/edit

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM