parse JSON Map in JQuery

jquery, json

Solution

Using jQuery's `.each()` to loop through the `key2` items.

var obj = $.parseJSON(yourJSONString);

$.each(obj["key2"], function(key, value){
    console.log(key); // <-- source, target
    $.each(value, function(arrKey, arrValue){
        console.log(arrValue); // <-- element1, element2 etc etc
    });
});

If you don't want to specify `key2` to target, and you want to go through all of the outer objects then:

$.each(obj, function(outerKey, outerValue){
    console.log(outerKey); // <-- key, key2
    $.each(outerValue, function(key, value){
        console.log(key); // <-- source, target
        $.each(value, function(arrKey, arrValue){
            console.log(arrValue); // <-- element1, element2 etc etc
        });
    });
});

You can also achieve the same without jQuery, by using the native `JSON.parse()` and nested vanilla `for(var=0; i<something.length; i++)` loops.

Problem

I have the following map where every key is a map which its values are lists as the following json: ``` { "key": { "source": ["element1", "element2"], "target": ["element1", "element2"] }, "key2": { "source": ["element1"], "target": ["element1"] } }​ ``` I want to do the following: Get key ( get("key2")) which will return the map Go over every key in this map( source and target) iterate over each item in the result list (element1, element2) How can I achieve this?

Original source