如何解决遍历深度嵌套的对象以生成html optgroup / options
我试图获取对象的键并创建一个optgroup(如果它包含子代),然后使optgroup成为子代选项。如果孩子也是一个对象,那么我想在父optgroup中嵌套另一个optgroup。下面是我的对象myTypes
let myTypes = {
women:
{
tops:
{
poloshirts:"polo shirts",tshirts: "t-shirts",buttondown: "button down",longsleeve:"long sleeve",vneck:"vneck",tanktop:"tanktop",blouse:"blouse",croptop:"croptop",drifit: "dri-fit",dressshirt:"dress shirt"
},bottoms:
{
shorts:"shorts",jeans:"jeans",joggers:"joggers",skirts:"skirts",dresspants:"dresspants",leggings:"leggings"
},shoes:
{
boots:"boots",sneakers: "sneakers",sandals:"sandals",flats:"flats",heels:"heels"
},jewelry:
{
rings: "rings",bracelets:"bracelets",necklaces: "necklaces",anklets: "anklets"
},sweaters: "sweaters",sweatshirts: "sweatshirts",hoodies: "hoodies",dresses:
{
sundress: "sundress",short: "short",long: "long",maxidress: "maxidress"
},accessories:
{
watches:"watches",glasses:
{
sunglasses: "sunglasses",reading:"reading"
},wallets: "wallets",keychains: "keychains",lanyards:"lanyards",belts:"belts",purses:"purses"
}
},men:
{
tops:
{
poloshirts:"polo shirts",dressshirt: "dress shirt"
},dresspants:"dress pants",flats:"flats"
},belts:"belts"
}
},kids:
{
girl:
{
tops:
{
poloshirts:"polo shirts",dressshirt:"dress shirt"
},bottoms:
{
shorts:"shorts",leggings:"leggings"
},shoes:
{
boots:"boots",heels:"heels"
},jewelry:
{
rings: "rings",anklets: "anklets"
},dresses:
{
sundress: "sundress",maxidress: "maxidress"
},accessories:
{
watches:"watches",glasses:
{
sunglasses: "sunglasses",reading:"reading"
},purses:"purses"
}
},boy:
{
tops:
{
poloshirts:"polo shirts",dressshirt: "dress shirt"
},flats:"flats"
},belts:"belts"
}
}
}
}
我尝试遍历此问题,然后使用适当的选项生成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);
解决方法
您需要知道,使用optgroup
元素嵌套在一起的方法是行不通的,因为只会显示optgroup
的第一级:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup
尝试使用类似的方法:
const path = (source = {}) => {
// Let the initial string be empty
let returnedString = '';
// Convert the object into an array using key/value pair and then iterate through it
Object.entries(source)
.forEach(([key,value]) => {
if (typeof value === 'object' && value !== null) {
// value is an object,iterate through it
returnedString += `<optgroup label="${key}">${path(value)}</optgroup>`;
} else {
// value should be a string
returnedString += `<option value="${key}">${value}</option>`;
}
});
// Return the string
return returnedString;
}
此外,在处理DOM时,建议使用内置方法来处理元素而不是字符串:
// Create the "root" element
// const root = document.createElement('select');
const path = (source = {},rootElement = undefined) => {
// Define the root element if not an instance of Element
const root= rootElement instanceof Element ? rootElement : document.createElement('select');
// Convert the object into an array using key/value pair and then iterate through it
Object.entries(source)
.forEach(([key,value]) => {
if (typeof value === 'object' && value !== null) { // value is an object,iterate through it
// Create an optgroup element
const optgroup = document.createElement('optgroup');
// Defines the attributes
optgroup.setAttribute('label',key);
// Add "content" inside the optgroup
path(value,optgroup);
// Append the newly created optgroup element to the root
root.appendChild(optgroup);
} else { // value should be a string
// Create an option element
const option = document.createElement('option');
// Defines the attributes
option.setAttribute('value',key);
option.text = value;
// Append the newly created option element to the root
root.appendChild(option);
}
});
// Return the root element
return root;
}
编辑1:为答案添加了DOM方法
编辑2:添加了optgroup
嵌套警告
function getMyTypes(obj_myTypes) {
var targetHTML = $("");
for (const key in obj_myTypes) {
if (obj_myTypes.hasOwnProperty(key)) {
var element = obj_myTypes[key];
console.log(key)
targetHTML.prepend(`<optgroup id="one" label="${key}"> ${key} </optgroup>`);
//each in obj
//console.log(element)
stepTwo(element)
}
}
}
getMyTypes(myTypes);
function stepOne() {
var step_one = $('optgroup').filter('[id="one"]');
step_one.each((index) => {
// var result = $(this).text()
step_one.prepend(`<optgroup id="two" label=""> two </optgroup>`)
});
}
stepOne()
function stepTwo(obj_elem) {
var step_two = $('optgroup').filter('[id="two"]');
for (const key in obj_elem) {
if (obj_elem.hasOwnProperty(key)) {
var item_of_element = obj_elem[key];
console.log('KEY: '+key)
step_two.each((index,html_element) => {
$(html_element).attr("label",value)
console.log(value)
//return value
});
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。