在javascript中迭代地图中的数组

时间:2015-02-25 18:12:08

标签: javascript arrays

我是javascript的新手,我无法绕过如何使用一组键来提取地图,然后从地图中的数组中提取值,而无需完全重新创建地图。我的两个数据结构看起来像。

var keys = ["key1","key2","key3"]

var data = {
"key1": {
    "target": "hostname",
    "datapoints": [
        [12, 1.42472334E9],
        [13, 1.424723355E9],
        [14, 1.42472337E9]]},
"key2": {
    "target": "hostname",
    "datapoints": [
        [15, 1.42472334E9],
        [16, 1.424723355E9],
        [17, 1.42472337E9]]}}

我试图提取数据点,将它们放入两个数组中,以便根据键进行绘图。试图迭代:

for (var k in key)
    for (var v in data[key][datapoints])

显然不是正确的做法。有没有更好的方法来获取数据而不撕裂地图?

3 个答案:

答案 0 :(得分:0)

如果您想要数组点数组,可以执行data.key1.datapoints[0]之类的操作。这将为您提供存储在key1下的数据点数组。

答案 1 :(得分:0)

您可以循环遍历数组keys,然后像这样提取datapoints

for (var i=0; i < keys.length; i++) {
    var datapoints = data[keys[i]].datapoints;
    // do whatever you want to do with the datapoints. 
    // It's not clear from your question.
}

答案 2 :(得分:0)

打开浏览器javascript控制台(按F12)以查看演示中的输出。

jsfiddle demo

var keys = ["key1","key2","key3"]

var data = {
"key1": {
    "target": "hostname",
    "datapoints": [
        [12, 1.42472334E9],
        [13, 1.424723355E9],
        [14, 1.42472337E9]]},
"key2": {
    "target": "hostname",
    "datapoints": [
        [15, 1.42472334E9],
        [16, 1.424723355E9],
        [17, 1.42472337E9]]}

}
//loop through the array named keys (mind that k is an index/integer)
for (var k in keys){
    //check if data has "key" as property (ie: key3 does not exist in data)
    if(data.hasOwnProperty(keys[k])){
        //loop through the array datapoints which is a property of the object named data 
        for ( var i =0; i< data[keys[k]]["datapoints"].length; i++){
          console.log(data[keys[k]]["datapoints"][i]); //outputs an array with 2 elements
        }
    }else{console.log(keys[k]+" does not exist in data")}

}