多维数组对象

时间:2015-05-18 11:14:03

标签: javascript multidimensional-array

我尝试使用JS访问多维数组中的元素。这似乎不起作用。请帮忙

var parsed = "";
 var myObject = [{
     firstname: "Jane",
     lastname: "Doe",
     email: "jdoe@email.com"
 }, {
     firstname: "Ja",
     lastname: "joe",
     email: "je@email.com"
 }];
 for (var prop in myObject) {
     parsed += prop + ": " + myObject[prop] + "\n";
 }
 alert(parsed);

3 个答案:

答案 0 :(得分:0)

您应该迭代数组并按名称选择适当的属性:

var parsed = "";
var myObject = [{
     firstname: "Jane",
     lastname: "Doe",
     email: "jdoe@email.com"
  },
  {
     firstname: "Ja",
     lastname: "joe",
     email: "je@email.com"
  },
];
for(var item in myObject)
{
  for (var prop in item) {
    parsed += prop + ": " + item[prop] + "\n";
  }
}

答案 1 :(得分:0)

你需要一个其他循环来迭代数组元素。

{{1}}

<强> DEMO

答案 2 :(得分:0)

以下是您的代码段 你的基本错误是myObject是一个对象数组,所以你必须遍历数组然后遍历给定索引中的对象

var attr,
        prop,
        parsed = "",
        myObject = [
            {
                firstname: "Jane",
                lastname: "Doe",
                email: "jdoe@email.com"
            },
            {
                firstname: "Ja",
                lastname: "joe",
                email: "je@email.com"
            }
        ];


// My object is an array
myObject.forEach(function(item, index, array) {

    // Verify to see that the property you want is yours and not inherited
    for (attr in item) {
        if (item.hasOwnProperty(attr)) {
            parsed += attr + ": " + item[attr] + "\n";
        }
    }

})

alert(parsed);