我有一个这样的对象:
var quantites = {
4: {
93: {
"id": "355",
"qty": 8
}
},
5: {
93: {
"id": "356",
"qty": 10
}
},
};
在不使用/知道要循环的键的情况下,如何在select中获取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));
});
});
发布于 2017-10-14 18:38:53
您可以首先将数据转换为对象数组,然后使用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>
发布于 2017-10-14 18:35:55
如果包含id和qty的对象始终位于第三级,并且没有其他对象,则可以将当前对象转换为具有id和qty的对象数组:
var quantites = {
4: {
93: {
"id": "355",
"qty": 8
}
},
5: {
93: {
"id": "356",
"qty": 10
}
},
};
var arrayOfQuantities =
Object.keys(quantites)
.map(
key =>
Object.keys(quantites[key])
.map(subKey => quantites[key][subKey])
)
.reduce((acc,item) => acc.concat(item),[])
首先解决如何获得这样一个不可用的对象并解决这个问题可能会更好。
发布于 2017-10-14 18:37:52
https://stackoverflow.com/questions/46743452
复制相似问题