我想知道在javascript中,最好是es6中,是否有一种很好的方法来将映射函数产生的字符串数组转换为动态创建的对象中的字段名。
例如,假设我从map函数中获得了以下结果:
["checkbox1Value", "checkbox4Value"]我想用这些结果来做这些事情:
const answer = {
//some other fields dynamically created
checkbox1Value: true,
checkbox4Value: true
}不管怎么说,这是通过es6完成的吗?
发布于 2018-02-08 22:55:48
您可以使用computed property names并映射单个对象,然后将其指定给单个对象。
var array = ["checkbox1Value", "checkbox4Value"],
object = Object.assign(...array.map(k => ({ [k]: true })));
console.log(object);
发布于 2018-02-08 22:53:46
let result = ["checkbox1Value", "checkbox4Value"];
const answer = result.reduce((acc, cur) => {acc[cur] = true; return acc}, {});
console.log(answer);
.reduce实际上只是一个花哨的for循环(一种"ES6方式“)。如果你想获得最大的效率,可以使用常规的for循环。
发布于 2018-02-08 22:54:01
const myArray = ["checkbox1Value", "checkbox4Value"];
let obj = {};
myArray.forEach(val => {
obj[val] = true;
})
console.log(obj);https://stackoverflow.com/questions/48688268
复制相似问题