我有一些 JSON 資料,它們是陣列中的大量物件,通過 PHPjson_encode()和 javascript fetch()API 獲取和輸出。此資料包括多對多資料透視表上的 MySQL 連接結果。本質上,它是輸出特定的影像板資料,您可以在多個板上擁有相同的影像,顯??然,多個板上。這一切都按預期作業。
背景關系
該資料的一個示例是:
[
{board_id: 428, board_name: 'tree board', image_id: 269}
{board_id: 428, board_name: 'tree board', image_id: 292}
{board_id: 426, board_name: 'Urban and City', image_id: 269}
{board_id: 426, board_name: 'Urban and City', image_id: 292}
{board_id: 426, board_name: 'Urban and City', image_id: 410}
{board_id: 365, board_name: 'random stuff', image_id: 269}
{board_id: 365, board_name: 'random stuff', image_id: 292}
]
在then()JavaScript 的一種方法中,fetch()我試圖根據這些資料創建一些按鈕元素,并將它們附加到父包裝器,其中每個board_id值只創建一個元素。
此輸出的 HTML應如下所示的示例:
<div class="wrapper">
<button value="428">tree board</button>
<button value="426">Urban and City</button>
<button value="365">random stuff</button>
</div>
問題
我無法解決的是如何在包裝器 div 中附加元素(最好使用模板字串),以便每個board_id值只有一個實體獲得按鈕元素?
在這樣的偽代碼中:
let newButton = `
<button value="${board_id}">${board_name}</button>
`
我很感激我需要在回圈中執行此操作——物件陣列被分配給方法json中的一個變數then():
let wrapper = document.querySelector('.wrapper'); // the wrapper div
json.forEach( i => {
let boardName = i.board_name;
let boardId = i.board_id;
// -- somehow only only create a button on one instance of each board_id value
// -- append the single instance of the button inside the wrapper div
})
我在想,在添加模板字串時,我需要在回圈中使用類似的東西嗎?
wrapper.insertAdjacentHTML('afterbegin', newButton);
問題摘要
如何僅為每個board_id值的一個實體輸出/創建一個按鈕元素,然后將其附加到父包裝器中?
非常感謝任何幫助或建議
uj5u.com熱心網友回復:
為了確保按鈕被捕獲以便創建兩個單獨的陣列:一個包含現有的板 ID,另一個包含按鈕 HTML。
使用回圈。如果板子 ID 不在 ids 陣列中,則添加它,然后將按鈕 HTML 添加到按鈕陣列中。然后join將按鈕排列起來,并將完整的 HTML 字串添加到包裝器元素中。
const data=[{board_id:428,board_name:"tree board",image_id:269},{board_id:428,board_name:"tree board",image_id:292},{board_id:426,board_name:"Urban and City",image_id:269},{board_id:426,board_name:"Urban and City",image_id:292},{board_id:426,board_name:"Urban and City",image_id:410},{board_id:365,board_name:"random stuff",image_id:269},{board_id:365,board_name:"random stuff",image_id:292}];
const wrapper = document.querySelector('.wrapper');
const ids = [];
const buttons = [];
for (const { board_id, board_name } of data) {
if (!ids.includes(board_id)) {
ids.push(board_id);
buttons.push(`<button value=${board_id}>${board_name}</button>`);
}
}
wrapper.innerHTML = buttons.join('');
<div class="wrapper">
</div>
附加檔案
- 解構賦值
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/530440.html
