如何从数组中获取第一个元素和第二个元素内的值

时间:2014-12-22 11:56:17

标签: javascript jquery

如何从

获取第一个元素和第二个元素内的值

更新(由于问题中的错误编辑)

var data = {
"0": [
    "The VehicleNumber has already been taken."
],
"2": [
    "The VehicleCode has already been taken."
]}

即,

首先=已经采取了0。

秒=已经采取了2。

4 个答案:

答案 0 :(得分:1)

这是JSON个对象。要从中获取任何价值,您需要知道key name,例如: - jsonObj["x"]jsonObj["y"]

但是,如果您不知道密钥名称,则将其迭代为: -

$.each(jsonObj,function(k,v){

//get value by using v or jsonObj[k];

});

更新以回应您的小提琴

var data={};
data["0"]=["The VehicleNumber field is required."];
data["1"]=["The NumberSeats field is required."];
data["2"]=["The VehicleCode field is required."];
data["3"]=["The MaximumAllowed field is required."];
data["4"]=["The City field is required."];
data["5"]=["The State field is required."];
data["6"]=["The Phone field is required."];
data["7"]=["The Insurance field is required."];
data["9"]=["The Address field is required."];

alert (data[1]);

检查这个小提琴http://jsfiddle.net/qbjbke03/8/

答案 1 :(得分:0)

我不确定我的问题是否正确,但不应该做以下工作?

console.log(myObj["y"][0] + " " + myObj["x"][0])

答案 2 :(得分:0)

    var data = '{
    "0": [
        "The VehicleNumber field is required."
    ],
    "1": [
        "The NumberSeats field is required."
    ],
    "2": [
        "The VehicleCode field is required."
    ],
    "3": [
        "The MaximumAllowed field is required."
    ],
    "4": [
        "The City field is required."
    ],
    "5": [
        "The State field is required."
    ],
    "6": [
        "The Phone field is required."
    ],
    "7": [
        "The Insurance field is required."
    ],
    "9": [
        "The Address field is required."
    ]
}';
    data = JSON.parse(data);
    alert (data[0]);
    alert (data[1]);

<强> JS Fiddle

答案 3 :(得分:0)

您在问题中提到的构造不是数组,而是对象。

要打印对象内的所有数组值,可以使用 -

var data = {
    "x": [ "The 0 has already been taken." ],
    "y": [ "The 2 has already been taken." ]
}
for (var key in data) {
  if (data.hasOwnProperty(key)) {
     console.log("First=",data[key][0]);
    }
}