遍历深度嵌套对象生成html optgroup/options

我正在尝试获取我的对象的键并创建一个 optgroup(如果它包含子项)然后创建 optgroup 的子项选项。如果一个孩子也是一个对象,那么我想在父 optgroup 中嵌套另一个 optgroup。下面是我的对象 myTypes

我试图遍历它,然后使用适当的选项生成 html 选择,但我无法弄清楚。我得到的最远的是这个


    let selectionHTML = "";

    let paths = (arr)=>{

        for(let i in arr){

            if(typeof arr[i] == "object" && arr[i] !== null){

                selectionHTML += "<optgroup label = '" + i + "'></optgroup>";

                paths(arr[i]);

            }

        }

    }

    paths(myTypes);

我不知道如何去生成我的代码。


不负相思意
浏览 142回答 2
2回答

千万里不及你

您需要知道使用嵌套optgroup元素的方法是行不通的,因为只会optgroup显示第一层:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup尝试使用类似的东西:const path = (source = {}) => {&nbsp; // Let the initial string be empty&nbsp; let returnedString = '';&nbsp; // Convert the object into an array using key/value pair and then iterate through it&nbsp; Object.entries(source)&nbsp; &nbsp; .forEach(([key, value]) => {&nbsp; &nbsp; &nbsp; if (typeof value === 'object' && value !== null) {&nbsp; &nbsp; &nbsp; &nbsp; // value is an object, iterate through it&nbsp; &nbsp; &nbsp; &nbsp; returnedString += `<optgroup label="${key}">${path(value)}</optgroup>`;&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // value should be a string&nbsp; &nbsp; &nbsp; &nbsp; returnedString += `<option value="${key}">${value}</option>`;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; // Return the string&nbsp; return returnedString;}此外,在操作 DOM 时,建议使用内置方法来操作元素而不是字符串:// Create the "root" element// const root = document.createElement('select');const path = (source = {}, rootElement = undefined) => {&nbsp; // Define the root element if not an instance of Element&nbsp; const root= rootElement instanceof Element ? rootElement : document.createElement('select');&nbsp; // Convert the object into an array using key/value pair and then iterate through it&nbsp; Object.entries(source)&nbsp; &nbsp; .forEach(([key, value]) => {&nbsp; &nbsp; &nbsp; if (typeof value === 'object' && value !== null) { // value is an object, iterate through it&nbsp; &nbsp; &nbsp; &nbsp; // Create an optgroup element&nbsp; &nbsp; &nbsp; &nbsp; const optgroup = document.createElement('optgroup');&nbsp; &nbsp; &nbsp; &nbsp; // Defines the attributes&nbsp; &nbsp; &nbsp; &nbsp; optgroup.setAttribute('label', key);&nbsp; &nbsp; &nbsp; &nbsp; // Add "content" inside the optgroup&nbsp; &nbsp; &nbsp; &nbsp; path(value, optgroup);&nbsp; &nbsp; &nbsp; &nbsp; // Append the newly created optgroup element to the root&nbsp; &nbsp; &nbsp; &nbsp; root.appendChild(optgroup);&nbsp; &nbsp; &nbsp; } else { // value should be a string&nbsp; &nbsp; &nbsp; &nbsp; // Create an option element&nbsp; &nbsp; &nbsp; &nbsp; const option = document.createElement('option');&nbsp; &nbsp; &nbsp; &nbsp; // Defines the attributes&nbsp; &nbsp; &nbsp; &nbsp; option.setAttribute('value', key);&nbsp; &nbsp; &nbsp; &nbsp; option.text = value;&nbsp; &nbsp; &nbsp; &nbsp; // Append the newly created option element to the root&nbsp; &nbsp; &nbsp; &nbsp; root.appendChild(option);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; // Return the root element&nbsp; return root;}编辑 1:在答案中添加了 DOM 方式optgroup编辑 2:添加嵌套警告

Qyouu

function getMyTypes(obj_myTypes) {&nbsp; &nbsp; var targetHTML = $("");&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for (const key in obj_myTypes) {&nbsp; &nbsp; &nbsp; &nbsp; if (obj_myTypes.hasOwnProperty(key)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var element = obj_myTypes[key];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(key)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; targetHTML.prepend(`<optgroup id="one" label="${key}"> ${key} </optgroup>`);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //each in obj&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //console.log(element)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stepTwo(element)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}getMyTypes(myTypes);function stepOne() {&nbsp; &nbsp; var step_one = $('optgroup').filter('[id="one"]');&nbsp; &nbsp; &nbsp; &nbsp; step_one.each((index) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// var result = $(this).text()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; step_one.prepend(`<optgroup id="two" label=""> two </optgroup>`)&nbsp; &nbsp; &nbsp; &nbsp; });}stepOne()function stepTwo(obj_elem) {&nbsp; &nbsp; var step_two = $('optgroup').filter('[id="two"]');&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for (const key in obj_elem) {&nbsp; &nbsp; &nbsp; &nbsp; if (obj_elem.hasOwnProperty(key)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var item_of_element = obj_elem[key];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('KEY: '+key)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; step_two.each((index,html_element) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(html_element).attr("label", value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //return value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript