[英]How can I instantiate a dictionary in Javascript where all keys map to the same value?
我有一個像這樣的數組:
let arr = ['ABC', 'DEF']
我想將該數組轉換為
let obj = {"ABC": 0, "DEF": 0}
進行這種轉換的合適的 ES6 語法是什么?
let arr = ['ABC', 'DEF']
arr.reduce(x => ({[x] : 0 }))
這很接近,但我最終得到{"ABC": 0}
基本上,我想獲取一個任意長度的數組,並將該數組中的所有值分配給“默認”值 0。
謝謝!
只需使用一個簡單的循環:
const arr = ['ABC', 'DEF'];
const obj = {};
for (const x of arr) obj[x] = 0;
如果你想變得花哨,我推薦Object.fromEntries
:
Object.fromEntries(arr.map(x => [x, 0]))
您只是在制作像 map 這樣的單個對象。 您需要繼續返回 object。
const arr = ['ABC', 'DEF'] const result = arr.reduce((o, k) => ({[k]: 0, ...o }), {}); console.log(result) const result2 = arr.reduce((o, k) => (o[k] = 0, o), {}); console.log(result2)
obj = arr.reduce((result, item, index) => {
result[item] = 0
return result
}, {})
希望這會對您有所幫助。 如果您有任何問題,請告訴我。
您可以只使用Array.reduce
並傳遞一個空的 object 作為初始值,如下面的代碼:
var arr = ["ABC","DEF"].reduce((a,b)=> (a[b]=0,a),{}); console.log(arr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.