2015-10-21 127 views
0

客户端有一个要求,即内容文本应以每个单独内容的新序列号开头。对于内容JSON,请考虑以下示例JSON。作为后端的响应,我将在前端获得此JSON。我迭代迭代该JSON,所以现在我想创建它的序列号,同时迭代它。有什么简单的方法来做到这一点?从json生成序列

var myobj = { 
"name": "sample",      //1 
"def": [        //2 
     { 
     "setId": 1,     //2.1.1 
     "setDef": [     //2.1.2 
      {   
       "type": "STRING",  //2.1.2.1.1 
       "name": "ABC"   //2.1.2.1.2 
      }, 
      { 
       "type": "STRING",  //2.1.2.2.1 
       "name": "XYZ"   //2.1.2.1.2 
      } 
     ] 
    }, 
    { 
     "setId": 2,     //2.2.1 
     "setDef": [     //2.2.2 
      { 
       "type": "STRING", //2.2.2.1.1 
       "name": "abc"  //2.2.2.1.2 
      }, 
      { 
       "type": "STRING", //2.2.2.2.1 
       "name": "xyz"  //2.2.2.1.1 
      } 
     ] 
    } 
], 
"property": {   //3 
    { 
     "color": "red" //3.1.1 
    }, 
    { 
     "run": true //3.2.1 
    }, 
    { 
     "width": [120, 330, 332] //3.3.1 
    } 
}, 
listing: true //4 

};

这里是我的代码:

function displayContent(obj) { 
    jQuery.each(obj, function(key, val) { 
     recursiveIterObj(key, val, obj); 
    }); 
} 
function recursiveIterObj(key, val, obj) { 
     if(!isplain(val)){ 
      setContentData(key, curr_seq, last_seq, ""); 
      $.each(val, function(k,v){ 
       recursiveIterObj(k, v, val); 
      }); 
     }else{ 
      setContentData(key, curr_seq, last_seq, val); 
     } 
} 

function isplain(data) { 
    return (typeof data === 'string' || typeof data === 'number')? 
     true:false; 
} 
function setContentData(key, curr_seq, last_seq, val){ 
      $(".heading").text(key); 
      $(".sequence").txt(curr_seq); // if this is 2.1.2 or 4 
      $(".sequence_last").txt(last_seq); // then, this should be 2.1.1 or 3 
      $(".txt_content").text(val); 
} 
$(function(){ 
displayContent(obj); 
}) 

注意 - 以上JSON是从互联网上随机JSON。

+0

JSON!== JavaScript Object – phuzi

+0

@yoshi no that trex – phuzi

+0

你的JSON无效,你可以检查它[这里](http://jsonlint.com) – MaxZoom

回答

1

JavaScript中不保证对象中的属性顺序。只有在数组的情况下,您将在JavaScript中迭代时看到顺序。

由于ECMAScript 2015,使用Map对象可能是一种替代方案。一个Map与Object有一些相似之处,并保证按键顺序。