迭代特定的json

时间:2012-02-28 13:58:54

标签: javascript iteration json

我需要在php中生成的json对象中使用以下结构迭代js(无框架):

    {
        EDITED: I DID HAVE AN ERROR, SORRY
    }

我搜索没有任何js框架的解决方案。 ¿如何获得,例如,

lvl1a.lvl2a.a
lvl1a.lvl2a.b
lvl1a.lvl2b.a
lvl1a.lvl2b.b
...

由于


更多信息:

我在上一个代码中出现了错误!抱歉

功能:填充两个select,“select1”和“select2”,选项= Category optgroup = CategoryParent

$toJson=array();
$selectname=array("select1","select2");
for($i=0;$i<2;$i++){
    $sql="SELECT idCategory as v,name as l,(select name from categories where idCategory=C.idCategoryParent) as p FROM categories C WHERE idBanner".($i+1)." is NULL order by idCategoryParent, `order`";
    $result =$ocdb->query($sql);
    $nameIdx = "";
    while ($row=mysql_fetch_assoc($result)){
        $first=mysql_field_name($result, 0);
        $second=mysql_field_name($result,1);
        $third= mysql_field_name($result,2);            

        if($nameIdx!=$row[$third])
                $nameIdx=$row[$third];
        }
            if($row[$third]!=NULL){
                array_pop($row);
                $toJson[$selectname[$i]][$nameIdx][]=$row;
            }

    }

}
$inJson=json_encode($toJson);

所以我得到类似的东西:

    {
        "select1":  {  "optgroup1":[{"v":"1","l":"option1"},{"v":"2","l":"option2"}],
                       "optgroup2":[{"v":"3","l":"option1"},{"v":"4","l":"option2"}],
                       "optgroup3":[{"v":"5","l":"option1"},{"v":"6","l":"option2"}]
                    },
        "select2":  {  " (...)
    }

// optgroup是parentCategory //选项是无父母的类别

2 个答案:

答案 0 :(得分:1)

你的意思是:

myObject.lvl1a.lvl2a[0].a
myObject.lvl1a.lvl2a[1].b

等等?

答案 1 :(得分:1)

使用递归的东西:

function iterateObject(obj){
  var result = [];

  function recurse(obj){
     for (var l in obj){
      if(obj.hasOwnProperty(l)){
       result.push( l+ 
                    (!(obj[l] instanceof Object) 
                     ? ': '+obj[l] 
                     : ' -> object >' ));
       if (obj[l] instanceof Object){
          recurse(obj[l]);
       }
      }
     }
  }

  recurse(obj);
  return result;
}

var thing = {
    "lvl1a":  {  "lvl2a":[{"a":"xxxxx"},{"b":"xxxxx"}],
                 "lvl2b":[{"a":"xxxxx"},{"b":"xxxxx"}],
                 "lvl2c":[{"a":"xxxxx"},{"b":"xxxxx"}]
              },
    "lvl1b":  {  "lvl3a":[{"c":"xxxxx"},{"d":"xxxxx"}],
                 "lvl3b":[{"c":"xxxxx"},{"d":"xxxxx"}],
                 "lvl3c":[{"c":"xxxxx"},{"d":"xxxxx"}]
              }
};
console.log(iterateObject(thing).join('\n'));
//=> 
// lvl1a -> object >
// lvl2a -> object >
// 0 -> object >
// a: xxxxx
// 1 -> object >
// b: xxxxx
// ... etc