我有一个这样的对象:
var quantites = {
4: {
93: {
"id": "355",
"qty": 8
}
},
5: {
93: {
"id": "356",
"qty": 10
}
},
};
如何在不使用/不知道要循环的键的情况下获取 id 作为值和 qty 作为选择中的标签:
<option value="335">8</option>
<option value="336">10</option>
到一个div:
<div id="qty">
<select></select>
</div>
到目前为止我尝试过的是:
$.each(quantites, function(key, value) {
$('#qty')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});
最佳答案
您可以先将数据转换为对象数组,然后使用 forEach
循环添加到 select
var quantites = {"4":{"93":{"id":"355","qty":8}},"5":{"93":{"id":"356","qty":10}}}
var select = $('#qty select')
var data = [].concat(...Object.values(quantites).map(Object.values))
data.forEach(function(e) {
select.append(`<option value="${e.id}">${e.qty}</option>`)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="qty">
<select></select>
</div>
关于javascript - 如何获取对象值和 id 作为选择框的选项使用 javascript 或 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46743452/