JavaScript Several methods of looping about JSON collections

Source: Internet
Author: User

/** * Generate the option tree control based on JSON data * If a children node is automatically generated tree data * @param {JSON} data * @param {int} n node Depth * @param {string} char node Name prefix * @returns {string} * @since 1.0 2014-8-22 by Sutroon * @example * var data = (typeof (data) = = "Object")? Data: $.parsejson (data); * var str = '; * Str=generate_options (data); */functionGenerate_options (data, N,Char) {    if(n = =undefined) {N= 0; }    if(Char==undefined) {        Char= ' ... '; }    varPad = ';  while(N > 0) {Pad+=Char; N--; }    varstr = "; if(data.length) {//multi-line format         for(vari = 0; i < data.length; i++) {            if(data[i].id) {//for [{"id": "1", "name": "Name1"}] formatstr + = ' <option value= ' + data[i].id + ' > ' + Pad + (data[i].name? Data[i].name:data[i].text) + ' </option> '; } Else if(data[i].item) {//for [{"Item": "1"},{"item": "2"}]str + = ' <option value= "' + Data[i].item + '" > ' + pad + data[i].item + ' </option> '; } Else {                //format for {"Item1", "item2"}str + = ' <option value= "' + data[i] + '" > ' + Pad + data[i] + ' </option> '; }            if(data[i].children) {str+ = Generate_options (Data[i].children, n + 1,Char); }        }    }    Else {        //for {"A": "A1", "B": "B2"} single-line format         for(varattrinchdata) {STR+ = ' <option value= ' + attr + ' "> ' + data[attr] + ' </option> '; }    }    returnstr;}

Copyright NOTICE: This article is the original Tian Lan (14507247#qq.com), copyright follow the Knowledge sharing license agreement [view]. You can freely reprint the collection, but please leave this statement, thank you!

JavaScript Several methods of looping about JSON collections

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.