2

I want to convert hash to array by javascript function in one line

a is hash which have value are

Object { 10="aa", 11="bb"} 

and i want to convert it into

a=[10,"aa",11,"bb"] 

Is there any methods which can convert it into array

0

    3 Answers 3

    1

    Like this?

    var obj = { 10: "aa", 11: "bb"}; var array = []; for( i in obj ) { array.push(i); array.push(obj[i]); } 
      1
      var ob={10:"aa", 11:"bb"}; a = []; 

      one line

      for(o in ob) a.push(Number(o), ob[o]); 
      1
      • What is the reason for adding 2 spaces to an answer?
        – QuentinUK
        CommentedMar 8, 2013 at 18:56
      0

      For instance:

      var obj = { 10: 'aa', 11: 'bb' }; 

      to translate that into the Array you want, we can go like

      var array = Object.keys( obj ).map(function( name ) { return [ +name ? +name : name, obj[ name ] ]; }).reduce(function( a, b ) { return a.concat(b); });