gpt4 book ai didi

javascript - 列出按键分组的数组内容

转载 作者:数据小太阳 更新时间:2023-10-29 04:52:09 25 4
gpt4 key购买 nike

如果我的术语不正确,我深表歉意——这绝对不是我的专业领域。

我想制作一个 <select>从 json 文件中列出,并将条目分组在 <optgroup> 中由一把 key 。我已经成功地列出了选择中的所有条目,但不知道如何循环遍历并将项目嵌套在它们的键下。

我的 JSON 看起来像这样:

[
{
"Type" : "Overdrive",
"Brand" : "Chase Bliss",
"Name" : "Brothers",
"Width" : 2.75,
"Height" : 4.77,
"Image" : "public/images/pedals/chasebliss-brothers.png"
}
]

下面是我如何渲染 <select> :

window.RenderPedals = function(pedals){
for(var i in pedals) {
var $pedal = $("<option>"+ pedals[i].Brand + " " + pedals[i].Name +"</option>").attr('id', pedals[i].Name.toLowerCase().replace(/\s+/g, "-").replace(/'/g, ''));
$pedal.data('width', pedals[i].Width);
$pedal.data('height', pedals[i].Height);
$pedal.data('height', pedals[i].Height);
$pedal.data('image', pedals[i].Image);
$pedal.appendTo('.pedal-list');
}
}

我正在寻找的是这个标记:

<select>
<optgroup label="Chase Bliss">
<option data-width="..." data-height="..." data-image="...">Chase Bliss Brothers</option>
</optgroup>
</select>

谁能指出我正确的方向?

最佳答案

您可以使用对象解构获取当前对象的属性,无需 for..in循环,创建一个 <optgroup>带有 label 的元素属性设置为 "Brand" , 追加 <option><optgroup> , 追加 <optgroup><select> .检查是否 <optgroup>具有 label 的元素属性设置为 Brand存在,如果 true , 附加 <option>那个<optgroup> , 否则追加一个新的 <optgroup>元素到 <select>html设置为新 <option>元素。

var data = [{
"Type": "Overdrive",
"Brand": "Chase Bliss",
"Name": "Brothers",
"Width": 2.75,
"Height": 4.77,
"Image": "public/images/pedals/chasebliss-brothers.png"
}
, {
"Type": "Underdrive",
"Brand": "Bliss Chase",
"Name": "Sisters",
"Width": 5.72,
"Height": 7.74,
"Image": "public/images/pedals/chasebliss-sisters.png"
}
, {
"Type": "Throughdrive",
"Brand": "Bliss Chase",
"Name": "Cousins",
"Width": 2.75,
"Height": 4.74,
"Image": "public/images/pedals/chasebliss-cousins.png"
}
];

window.RenderPedals = function(pedals) {
var {Type, Brand, Name, Width, Height, Image} = pedals;
var option = $("<option>", {
text: `${Brand} ${Name}`,
id: Name.toLowerCase()
.replace(/(\s+)|(['"])/g, (m, p1, p2) => p1 ? "-" : ""),
data: {
width: Width,
height: Height,
image: Image
}
});
if ($("optgroup").is(`[label="${Brand}"]`)) {
$(`optgroup[label="${Brand}"]`).append(option);
} else {
$("<optgroup>", {
label: Brand,
html: option
}).appendTo(".pedal-list");
}
}

data.forEach(RenderPedals);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<select class="pedal-list"></select>

关于javascript - 列出按键分组的数组内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42539350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com