javascript 将数组转换为对象键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54789406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert array to object keys
提问by Miguel Stevens
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
将数组转换为以这些数组值作为键的对象的最佳方法是什么,空字符串作为新对象的值。
['a','b','c']
to:
到:
{
a: '',
b: '',
c: ''
}
回答by prasanth
try with Array#Reduce
尝试 Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((a,b)=> (a[b]='',a),{});
console.log(res)
回答by Maheer Ali
You can use Array.prototype.reduce()and Computed property names
您可以使用Array.prototype.reduce()和计算属性名称
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
回答by brk
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
您可以使用数组归约函数并在累加器中传递一个空对象。在这个累加器中添加由表示的键curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)
回答by Krzysztof Krzeszewski
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
您可以使用 Object.assign 属性来组合使用 map 函数创建的对象,请注意,如果数组元素的值不唯一,则后者将覆盖先前的
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
回答by Alexus
var target = {}; ['a','b','c'].forEach(key => target[key] = "");

