1

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?

  • I guess this is what you want: [How can I add a key/value pair to a JavaScript object literal?](http://stackoverflow.com/q/1168807/218196). JS doesn't have associative arrays, it has [**objects**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) – Felix Kling Nov 25 '14 at 18:06
  • Yes this is what I want, my apologies. My problem is the way that I am attempting to pull the values out of the array of objects and put them into the new Object is not working? –  Nov 25 '14 at 18:07
  • @FelixKling In a [general sense](https://en.wikipedia.org/wiki/Associative_array), JS does, they're just not called "associative arrays". – ajp15243 Nov 25 '14 at 18:08
  • @ajp15243: Mmmh, yeah. For me, the term "array" also implies an order (just like it works in PHP). However, the properties of an object are not ordered. But I guess an "associative array" is really just a dictionary, in which case I agree. – Felix Kling Nov 25 '14 at 18:10
  • 1
    @RichardDavy: I guess you don't want to do what I linked to. It seems you are just having problems with the `for...in` loop. Have a look at the documentation to learn how it works: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Example – Felix Kling Nov 25 '14 at 18:13
  • @FelixKling I've never liked the term "associative array" anyway, since it is easily confused by some with a normal array. – ajp15243 Nov 25 '14 at 18:13
  • @FelixKling Didn't say I didn't, I wasn't having problems with the for loop either, I was having a problem with getting the object key and value from inside the array of objects, I apologize if I didn't make that clear, I also apologize for using the term associative array, I learned it as that name because you have an association of a name that you use for association for the key and value, hence associative array. What I was doing in my absence however was testing other ideas while you guys were doing the same, I don't like to sit idol while waiting so I work. It's why I didn't respond yet. –  Nov 25 '14 at 18:20

1 Answers1

0

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

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144