Converting JavaScript object with numeric keys into array

前端 未结 16 2418
-上瘾入骨i
-上瘾入骨i 2020-11-22 03:09

I have an object like this coming back as a JSON response from the server:

{\"0\":\"1\",\"1\":\"2\",\"2\":\"3\",\"3\":\"4\"}

I want to conv

相关标签:
16条回答
  • 2020-11-22 03:36

    Here is an example of how you could get an array of objects and then sort the array.

      function osort(obj)
      {  // map the object to an array [key, obj[key]]
        return Object.keys(obj).map(function(key) { return [key, obj[key]] }).sort(
          function (keya, keyb)
          { // sort(from largest to smallest)
              return keyb[1] - keya[1];
          }
        );
      }
    
    0 讨论(0)
  • 2020-11-22 03:39
    var json = '{"0":"1","1":"2","2":"3","3":"4"}';
    
    var parsed = JSON.parse(json);
    
    var arr = [];
    
    for(var x in parsed){
      arr.push(parsed[x]);
    }
    

    Hope this is what you're after!

    0 讨论(0)
  • 2020-11-22 03:39

    There is nothing like a "JSON object" - JSON is a serialization notation.

    If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray() method:

    var obj = {"0":"1","1":"2","2":"3","3":"4"};
    var yourArray = _(obj).toArray();
    
    0 讨论(0)
  • 2020-11-22 03:39

    Nothing hard here. Loop over your object elements and assign them to the array

    var obj = {"0":"1","1":"2","2":"3","3":"4"};
    var arr = [];
    for (elem in obj) {
       arr.push(obj[elem]);
    }
    

    http://jsfiddle.net/Qq2aM/

    0 讨论(0)
  • 2020-11-22 03:39
    var obj = {"0":"1","1":"2","2":"3","3":"4"};
    
    var vals = Object.values(obj);
    
    console.log(vals); //["1", "2", "3", "4"]
    

    Another alternative to the question

    var vals = Object.values(JSON.parse(obj)); //where json needs to be parsed
    
    0 讨论(0)
  • 2020-11-22 03:40

    This is best solution. I think so.

    Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})
    
    0 讨论(0)
提交回复
热议问题