Converting JavaScript object with numeric keys into array

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

    Try this:

    var newArr = [];
    $.each(JSONObject.results.bindings, function(i, obj) {
        newArr.push([obj.value]);
    });
    
    0 讨论(0)
  • 2020-11-22 03:22

    Assuming your have a value like the following

    var obj = {"0":"1","1":"2","2":"3","3":"4"};
    

    Then you can turn this into a javascript array using the following

    var arr = [];
    json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
    arr = $.parseJSON(json); //convert to javascript array
    

    This works for converting json into multi-diminsional javascript arrays as well.

    None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.

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

    You can convert json Object into Array & String using PHP.

    $data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';
    
    $b=json_decode($data);
    
    $i=0;
    while($b->{'resultList'}[$i])
    {
        print_r($b->{'resultList'}[$i]->{'displayName'});
        echo "<br />";
        $i++;
    }
    
    0 讨论(0)
  • 2020-11-22 03:31

    You simply do it like

    var data = {
        "0": "1",
        "1": "2",
        "2": "3",
        "3": "4"
    };
    var arr = [];
    for (var prop in data) {
        arr.push(data[prop]);
    }
    console.log(arr);
    

    DEMO

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

    Using raw javascript, suppose you have:

    var j = {0: "1", 1: "2", 2: "3", 3: "4"};
    

    You could get the values with:

    Object.keys(j).map(function(_) { return j[_]; })
    

    Output:

    ["1", "2", "3", "4"]
    
    0 讨论(0)
  • 2020-11-22 03:34
          var data = [];
    
          data  = {{ jdata|safe }}; //parse through js
          var i = 0 ;
          for (i=0;i<data.length;i++){
             data[i] = data[i].value;
          }
    
    0 讨论(0)
提交回复
热议问题