Converting JavaScript object with numeric keys into array

前端 未结 16 2417
-上瘾入骨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:43

    It's actually very straight forward with jQuery's $.map

    var arr = $.map(obj, function(el) { return el });
    

    FIDDLE

    and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map

    var arr = Object.keys(obj).map(function(k) { return obj[k] });
    

    FIDDLE

    That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.

    In ES2015 there's Object.values to the rescue, which makes this a breeze

    var arr = Object.values(obj);
    
    0 讨论(0)
  • 2020-11-22 03:43

    Not sure what I am missing here but simply trying the below code does the work. Am I missing anything here?

    https://jsfiddle.net/vatsalpande/w3ew5bhq/

    $(document).ready(function(){
    
    var json = {
       "code" :"1", 
       "data" : { 
        "0" : {"id":"1","score":"44"},
        "1" : {"id":"1","score":"44"}
        }
      };
    
      createUpdatedJson();
    
      function createUpdatedJson(){
    
        var updatedJson = json;
    
        updatedJson.data = [updatedJson.data];
    
        $('#jsondata').html(JSON.stringify(updatedJson));
    
    
        console.log(JSON.stringify(updatedJson));
      }
     })
    
    0 讨论(0)
  • 2020-11-22 03:44

    You can use Object.assign() with an empty array literal [] as the target:

    const input = {
      "0": "1",
      "1": "2",
      "2": "3",
      "3": "4"
    }
    
    const output = Object.assign([], input)
    
    console.log(output)

    If you check the polyfill, Object.assign(target, ...sources) just copies all the enumerable own properties from the source objects to a target object. If the target is an array, it will add the numerical keys to the array literal and return that target array object.

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

    var JsonObj = {
      "0": "1",
      "1": "2",
      "2": "3",
      "3": "4"
    };
    
    var array = [];
    for (var i in JsonObj) {
      if (JsonObj.hasOwnProperty(i) && !isNaN(+i)) {
        array[+i] = JsonObj[i];
      }
    }
    
    console.log(array)

    DEMO

    0 讨论(0)
提交回复
热议问题