Feras Odeh
Feras Odeh

Reputation: 9296

parse JSON Map in JQuery

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:

  1. Get key ( get("key2")) which will return the map

  2. Go over every key in this map( source and target)

  3. iterate over each item in the result list (element1, element2)

How can I achieve this?

Upvotes: 2

Views: 13093

Answers (3)

Ayman Safadi
Ayman Safadi

Reputation: 11552

Not sure if this is what you needed, but it should lead you down the right path:

var things = {
  "key": {
    "source": ["element1", "element2"],
    "target": ["element1", "element2"]
  },
  "key2": {
    "source": ["element1"],
    "target": ["element1"]
  }
};

var get = function( key ) {
    var output = '';

    for( thisKey in things ) {
        if( thisKey === key ) {
            var myThing = things[ key ];

            for( thingKey in myThing ) {
                output += thingKey + ': ' + myThing[thingKey].join(', ') + '<br />';
            }

            return output;
        }
    }
}

document.write( get( 'key' ));
document.write('<hr />');
document.write( get( 'key2' ));

Demo: http://jsfiddle.net/RucB3/

Upvotes: 0

MrCode
MrCode

Reputation: 64526

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.

Upvotes: 5

Parv Sharma
Parv Sharma

Reputation: 12705

var o = {
  "key": {
    "source": ["element1", "element2"],
    "target": ["element1", "element2"]
  },
  "key2": {
    "source": ["element1"],
    "target": ["element1"]
  }
}​
var key = o.key2;
for(p in key)
{
 elementArray = key[p];
 for(var i=0;i<elementArray.length;i++)
 {
   //access element 1 and 2 here
 }
}

Upvotes: 0

Related Questions