开发者

How do I push the keys from an object to an array?

开发者 https://www.devze.com 2023-03-02 22:46 出处:网络
Suppose I have the following object obj: obj开发者_Go百科 = { \'key1\' : [\'1\',\'2\',\'3\'], \'key2\' : [\'1\',\'2\',\'9\'],

Suppose I have the following object obj:

obj开发者_Go百科 = {
    'key1' : ['1','2','3'],
    'key2' : ['1','2','9'],
    'key3' : ['1','3','5']
}

How can I transform obj into two arrays that look like the following?

allOfTheKeys = ['key1','key2','key3']

allOfTheArrays = ['1','2','3','5','9']


Something like

allKeys = [];
allElems = [];

for(var k in obj){
   allKeys.push(k);
   for(var e in obj[k]){
      allElem.push(e)
   }
}

Actually, in jQuery you can do it more concisely using each() (warning, this isn't tested code):

jQuery.each(obj,function(key){
    allKeys.push(key); 
    jQuery.each(obj[key],function(elem){
        allElems.push(elem);
    }
});

Okay, you don't want repeats, add in

if(!(elem in allElems)) allElems.push(elem);


As I saw, other answers return repeated values. Here you have the solution (tested):

var allOfTheKeys = [], allOfTheArrays = [], nonRepeatedElems = {};
for(var key in obj){
   allOfTheKeys.push(key);
   for(var i=0; i< obj[key].length; i++)
      nonRepeatedElems[obj[key][i]] = true;
}
for(var e in nonRepeatedElems )
   allOfTheArrays.push(e);

If someone's wondering what nonRepeatedElems is, it's a hash table for the array values, whose key is the array element value. So I don't get repeated elements.

If you want your values to be ordered, just call allOfTheArrays.sort(); in the end.

EDIT: @float, Here you have a more understandable solution:

var allOfTheKeys = [], allOfTheArrays = [];
for(var key in obj){
   allOfTheKeys.push(key);
   for(var i=0; i< obj[key].length; i++){
      var arrayElem = obj[key][i];
      if(!$.inArray(arrayElem, allOfTheArrays)) //Add to the array if it doesn't exist yet
         allOfTheArrays.push(arrayElem);
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消