weixin_33749242 2015-11-18 12:16 采纳率: 0%
浏览 73

如何解析分组的json?

我有一个JSON结构:

{
 "2014": [
  "2014-01",
  "2014-02",
  "2014-03",
  ...
],
 "2015": [
  "2015-01",
  "2015-02",
  "2015-03",
  ...
]
}

...并且需要将该JSON解析为这样的HTML结构,不管有没有jQuery。

<select name="valueAA" id="valueAA">
    <optgroup label="2014">
        <option value="2014-01">Jan 2014</option>
        <option value="2014-02">Feb 2014</option>
        <option value="2014-03">Mar 2014</option>
                ...
    </optgroup>
    <optgroup label="2015">
        <option value="2015-01">Jan 2015</option>
        <option value="2015-02">Feb 2015</option>
        <option value="2015-03">Mar 2015</option>
                ...
    </optgroup>
</select>

谢谢!

  • 写回答

4条回答 默认 最新

  • bug^君 2015-11-18 12:31
    关注

    You can do this with a bit of jQuery and moment.js for your date formatting:

    fiddler

    HTML:

    <select id="dates"></select>
    

    JS:

    var object = {
        "2014": [
          "2014-01",
          "2014-02",
          "2014-03"
        ],
        "2015": [
            "2015-01",
            "2015-02",
            "2015-03"
        ]
    };
    
    var $select = $('#dates');
    
    $.each(object, function(year, dates) {
        var $optgroup = $('<optgroup/>').attr('label', year);
        $.each(dates, function(key, date) {
            $optgroup.append( 
                $('<option/>')
                    .val(date)
                    .text( moment(date, 'YYYY-MM').format('MMM YYYY') )
            );
        });
        $select.append($optgroup);
    });
    
    评论

报告相同问题?