想象一下,我有一組選定的復選框。每個都有一個與過濾器對應的值和名稱。
<input class="filter-item--checkbox" type="checkbox" name="colors" value="blue">
<input class="filter-item--checkbox" type="checkbox" name="colors" value="orange">
<input class="filter-item--checkbox" type="checkbox" name="items" value="chair">
<input class="filter-item--checkbox" type="checkbox" name="items" value="bed">
<input class="filter-item--checkbox" type="checkbox" name="material" value="plastic">
<input class="filter-item--checkbox" type="checkbox" name="material" value="wood">
如何將這些排序為一個陣列,如下所示?
const filters = [
'colors': [ 'blue', 'orange'],
'items': ['chair', 'bed'],
'material': ['plastic', 'wood'],
]
uj5u.com熱心網友回復:
您可以獲取元素并構建陣列物件。
const result = {};
for (const { name, value } of document.getElementsByClassName('filter-item--checkbox')) {
(result[name] ??= []).push(value);
}
console.log(result);
<input class="filter-item--checkbox" type="checkbox" name="colors" value="blue">
<input class="filter-item--checkbox" type="checkbox" name="colors" value="orange">
<input class="filter-item--checkbox" type="checkbox" name="items" value="chair">
<input class="filter-item--checkbox" type="checkbox" name="items" value="bed">
<input class="filter-item--checkbox" type="checkbox" name="material" value="plastic">
<input class="filter-item--checkbox" type="checkbox" name="material" value="wood">
uj5u.com熱心網友回復:
對于 OP 的用例,據說解決方案應該針對剛剛選中的復選框控制元件,人們可以/應該將FormDataWeb-API及其entries方法與reduce任務一起使用。將表單參考直接傳遞給FormData建構式可確保只有活動控制元件資料成為表單資料物件的一部分。因此,表單資料物件不會反映未選中復選框控制元件的名稱/鍵和值。
const formData = new FormData(document.forms[0]);
console.log(
Array
.from(
formData.entries()
)
.reduce((result, [key, value]) => {
const groupedValueList = (result[key] ??= []);
groupedValueList.push(value);
return result;
}, {})
);
.as-console-wrapper { min-height: 85%!important; }
<form>
<input type="checkbox" name="colors" value="blue" checked/>
<input type="checkbox" name="colors" value="orange" checked/>
<input type="checkbox" name="items" value="chair" checked/>
<input type="checkbox" name="items" value="bed" checked/>
<input type="checkbox" name="material" value="plastic" checked/>
<input type="checkbox" name="material" value="wood" checked/>
</form>
如果收集所有分組的復選框值而不管它們的checked狀態,只需要稍微改變上述方法......
console.log(
Array
.from(
document.querySelectorAll('form [type="checkbox"]')
)
.reduce((result, { name:key, value }) => {
const groupedValueList = (result[key] ??= []);
groupedValueList.push(value);
return result;
}, {})
);
.as-console-wrapper { min-height: 85%!important; }
<form>
<input type="checkbox" name="colors" value="blue" checked/>
<input type="checkbox" name="colors" value="orange"/>
<input type="checkbox" name="items" value="chair" checked/>
<input type="checkbox" name="items" value="bed"/>
<input type="checkbox" name="material" value="plastic" checked/>
<input type="checkbox" name="material" value="wood"/>
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/346226.html
標籤:javascript 数组 目的
