![](/img/trans.png)
[英]Create java script array dynamically whose name is in java script string
[英]Create a dict from a array in java script
這似乎很簡單,但我找不到這樣做的方法......
我在 javascript 中有一個數組,就像這樣
array = ["a","b","c"]
我想動態地構建一個基於它的新字典來擁有類似的東西
my_dict = {
"a": null,
"b": null,
"c": null
}
它看起來很基本,但我無法理解這一點。 我試過這樣的事情:
my_dict = {};
for (let key in array){
this.my_dist[key] = null;
}
但不幸的是,它沒有奏效。
使用Object.assign
和map
const array = ["a", "b", "c"]; const obj = Object.assign({}, ...array.map((x) => ({ [x]: null }))); console.log(obj);
你可以使用減少 function
let dict = your_array.reduce((map, init) => {
map[init] = null;
return map;
}, {});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.