我在頁面加載時對我的資料庫執行 GET 提取請求,并希望僅顯示 True 專案。
回應 json 物件有 32 個從 API 回傳的專案。它們都是鍵值對(帶有布林值),例如:
{
Apple: false
Banana: false
Orange: true
Kiwi: true
}
我只需要找到真正的專案,為每個真正的專案創建一個按鈕元素,從鍵設定按鈕文本標簽,并將其添加到我的頁面中的空 div 中。
我玩過 If/Else 并將 Object 轉換為帶有 Object.entries 的陣列 - 但我超出了我的深度并且不知道正確的方法。
任何幫助表示贊賞。干杯
(僅限香草 JS)
uj5u.com熱心網友回復:
您可以使用陣列方法array.filter()來過濾真實值。
然后選擇空的 div,迭代過濾后的資料并使用document.createEelementdocument.getElementById('container')創建按鈕元素,然后從鍵添加文本并將按鈕附加到容器 div。
const obj = {
Apple: false,
Banana: false,
Orange: true,
Kiwi: true,
};
const data = Object.entries(obj).filter(([key, value]) => value);
const container = document.getElementById('container');
data.forEach(item => {
const button = document.createElement('button');
button.innerText = item[0];
container.append(button);
});
#container button {
margin: 10px;
}
<div id="container"> </div>
uj5u.com熱心網友回復:
在 javascript 中,您可以使用 Object.entries() 來迭代物件并獲取它們的鍵和值。
const obj = {
Apple: false,
Banana: false,
Orange: true,
Kiwi: true
}
const results = [];
for (const [fruit,boolean] of Object.entries(obj)) {
if (boolean) results.push(fruit);
}
console.log(`There are ${results.length} 'true' in the given obj.\nThey are:\n${results.join(',\n')}`)
// output:
// There are 2 'true' in the given obj.
// They are:
// Orange,
// Kiwi
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/534467.html
上一篇:無法使用不記名令牌獲取資料
