JavaScript:如何访问多维数组?

时间:2016-02-17 23:29:57

标签: javascript arrays multidimensional-array

我已经创建了一个多维数组,通过在其他人中推送数组,但现在我无法从中检索数据,我有一个包含它的变量,但现在我需要处理它,我不能得到的值不是以下方式:

1

obj = JSON.parse(myArrayVariable);
alert(obj[0].origin);

2

alert(myArrayVariable[0]["origin"]);

我尝试了很多其他方法,但所有方法都给出了相同的结果,#34; UNDEFINED",我真的很讨厌这个词。我并不匆忙,但这让我好奇,因为我'我已经尝试了几天,我被困在这里。

任何人都可以帮我一把吗?谢谢堆垛机!

数组看起来像这样

[
    [
        {
            "origin": "4",
            "destination": "0",
            "scales": 1
        }
    ],
    [
        {
            "option": 1,
            "origin": "4",
            "destination": "3",
            "line": "l3",
            "direction": "3",
            "stops": "4,3",
            "stopcount": 2
        }
    ],
    [
        {
            "option": 1,
            "origin": "3",
            "destination": "0",
            "line": "l2",
            "direction": "0",
            "stops": "3,2,0",
            "stopcount": 3
        },
        {
            "option": 2,
            "origin": "3",
            "destination": "0",
            "line": "l0",
            "direction": "0",
            "stops": "3,0",
            "stopcount": 2
        }
    ]
]

1 个答案:

答案 0 :(得分:0)

首先,你必须展平这个array of array(多维数组)

function flatten(arr) {
    var self=this;
    return arr.reduce(function(acc, val) {
        return acc.concat(val.constructor === Array ? self.flatten(val) : val);
    },[]);
  }

以获得一维array

flatten( myArrayVariable )
[Object, Object, Object, Object]

此时你已经拥有它了

flatten(arr)[0]["origin"]
"4"

根据您的操作,您可以使用forEach

flatten(arr).forEach(function(item) { console.log( item ) })

遍历它:

Object {origin: "4", destination: "0", scales: 1}
Object {option: 1, origin: "4", destination: "3", line: "l3", direction: "3"…}
Object {option: 1, origin: "3", destination: "0", line: "l2", direction: "0"…}
Object {option: 2, origin: "3", destination: "0", line: "l0", direction: "0"…}