2

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?

4

3 回答 3

5

使用 jQuery.each()循环遍历key2项目。

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

如果您不想指定key2目标,并且想要遍历所有外部对象,则:

$.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
        });
    });
});

您也可以在没有 jQuery 的情况下通过使用本机JSON.parse()和嵌套的 vanillafor(var=0; i<something.length; i++)循环来实现相同的目的。

于 2012-12-26T19:28:12.580 回答
0
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
 }
}
于 2012-12-26T19:23:25.203 回答
0

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/

于 2012-12-26T19:42:56.743 回答