简体   繁体   中英

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

You guys never let me down and I am kind of in a tight spot on this one, I needed to maintain the order of a java map while converting it into a JSON object, I realized that this was nearly impossible and decided that I would use a JSON array. The only way that this would work for my particular data however was to use a JSON array of JSON objects. so it looks like this:

[{"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}]

the code that got me here:

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;
}

Hope my code is up to par, trying to keep it as clean as possible??? However back to the issue. This works great, the problem I am having however is converting this array of objects into an associative array in javascript so that I can use it for my D3js bar graph here is the code that I foolishly tried but failed with

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;
};

Any Ideas?

Try this

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 is Array not Object and you should not use for (..in..) (for(..in..) statement iterates over the enumerable properties of an object). In my example I use Object.keys which return array of keys in object, and you can get value by key in Object because in JS for get property from object there are two ways like obj.key or obj[key];

Demo: http://jsbin.com/ruseja/1/edit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM