0
 var Mydata =
        {
            "prop1":
                    [
                        { "a": "parties", "b": "0.006" , "c": "0.9"},
                        { "a": "royal-challenge",  "b": "0.02" , "c": "0.333" },
                        { "a": "star-speak","b": "0.02","c":"0.1" }
                    ],
            "prop2":
                    [
                        { "a": "parties","b": "0.006" , "c": "0.9"},
                        { "a": "star-speak","b": "0.02", "c": "0.009" }
                    ],
            "prop3":
                    [
                        { "a": "parties","b": "0.006" , "c": "0.9"}
                    ]
        };

我的目标是返回 a,b,c 的值,如下所示--->

parties,0.006,0.9
royal-challenge,0.02,0.333 and so on for all the properties.

我在迭代中遇到问题。

我正在做这样的事情---:

for(var i in Mydata){
           return i[a],i[b],i[c]
        }
4

4 回答 4

1

您可以使用for..in循环遍历键,检查数组,然后循环数组项。像这样的东西?

var newArray = []; // store the results in a new array

for (key in Mydata) { // loop prop1, prop2 etc
    if (Mydata[key].forEach) { // check for array
        Mydata[key].forEach(function(item) { // loop array
            newArray.push(item.a + ", " + item.b + ", " + item.c);
        });
    }
}

http://jsfiddle.net/CR2vY/

注意:该forEach方法在较旧的浏览器(如 ie8)中不可用,但很容易填充。更多信息请访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

于 2013-07-05T10:07:09.487 回答
0
for(var head in Mydata) {


    for(var leave in Mydata[head]) {
        document.write(Mydata[head][leave]['a']);
        document.write(',');
        document.write(Mydata[head][leave]['b']);
        document.write(',');
        document.write(Mydata[head][leave]['c']);
    }
}
于 2013-07-05T10:17:05.177 回答
0

试试这个(它应该适用于所有浏览器),结果数组将包含您可以迭代的所有对象

var result = [];
for (var key in Mydata) {
   if (Mydata.hasOwnProperty(key)) {
    for (var key2 in Mydata[key]) {
        if (Mydata[key].hasOwnProperty(key2)) {
          console.log(key2, Mydata[key][key2]);
          result.push(Mydata[key][key2]);
        }
    }  
   }
}
result;
于 2013-07-05T10:26:07.537 回答
0

尝试这个。

for(var index in Mydata){
   var propArray = Mydata[index];
   for(var i=0; i<propArray.length; i++){
      var prop = propArray[i];
      var opString = '';
      for(var propIndex in prop){
          opString +=prop[propIndex]+',';
      }
      console.log(opString.substr(0, opString.length-1))
   }

}
于 2013-07-05T10:12:17.923 回答