如何在javascript中转换数组中的hashmap值?

时间:2014-11-12 04:54:16

标签: javascript jquery json

考虑以下json值:

{"Operator":{"DT5241":{"name":"LESLIE, Alec "},"DT3709":{"name":"DAWSON, Peter"},"DT4206":{"name":"PEPWORTH, Jasmine"}

如何将其转换为数组?

我试过这样做:运营商是我的arr2 [3]

var array = $.map(arr2[3], function(value, index) {
    return [value];
});

但它没有帮助。它给出了这样的价值:

0:Object
 DT5241:Object
 DT3709:Object
 DT4206:Object

我只需要数组列表。

这很有效。 但它没有为我的表插入价值:

     var dataArray2 = [['TruckName', 'OperatorName']];
     for (var i = 3; i < arr2.length; i++) {
     for (var j = 0; j < array.length; j++){
     dataArray2.push([array[i], array[i].name]);
     }

1 个答案:

答案 0 :(得分:0)

我认为问题是arr2[3]是具有Operator键的对象的1个项目的对象,因此您需要遍历arr2[3].Operator

&#13;
&#13;
var arr2 = [];
arr2[3] = {
  "Operator": {
    "DT5241": {
      "name": "LESLIE, Alec "
    },
    "DT3709": {
      "name": "DAWSON, Peter"
    },
    "DT4206": {
      "name": "PEPWORTH, Jasmine"
    }
  }
}

var array = $.map(arr2[3].Operator, function(value, key) {
  var obj = {};
  obj[key] = value;
  return obj;
});
console.log(array)
$('#result').html(JSON.stringify(array))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
&#13;
&#13;
&#13;