什么是从这个状态精确转换的最佳方式?
["access","edit","delete"]
转换为:
{access:true, edit:true, update:true}
目前我需要循环遍历对象为每个值赋值,但我想知道lodash是否已提供此功能。
["access","edit","delete"]
转换为:
{access:true, edit:true, update:true}
目前我需要循环遍历对象为每个值赋值,但我想知道lodash是否已提供此功能。
const input = ["access","edit","delete"];
console.log(
input.reduce((obj, key) => { obj[key] = true; return obj; }, {})
);
With the new es6 spread syntax, you can even make this easier:
const input = ["access","edit","delete"];
console.log(
input.reduce((obj, key) => ({...obj, [key]: true}), {})
);
LODASH
您可以将其映射到条目数组,然后简单地使用lodash
的fromPairs
方法。
_.fromPairs(input.map(k=>[k, true]))
var input = ["access","edit","delete"];
var res = _.fromPairs(input.map(k=>[k,true]));
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
ES6
您可以将输入映射到键(每个输入)值(true)对的对象并进行分配。
Object.assign( ...input.map(k=>({[k]: true})))
var input = ["access","edit","delete"]
var res = Object.assign( ...input.map(k=>({[k]: true})));
console.log(res);
如果您需要一个Map
对象,可以将输入映射到条目(如lodash示例中所用),并简单构造一个新的Map,例如:
new Map(input.map(k=>[k, true]))
不需要为如此简单的事情导入库,只需将键数组reduce
成一个由这些键索引的对象:
const input = ["access","edit","delete"];
const output = input.reduce((a, key) => Object.assign(a, {[key]: true}), {});
console.log(output);
或者,将累加器的属性赋值而不是使用Object.assign
:
const input = ["access","edit","delete"];
const output = input.reduce((a, key) => {
a[key] = true;
return a;
}, {});
console.log(output);
_.mapValues()
来实现这个功能:
const input = ["access","edit","delete"];
const output = _.mapValues(_.keyBy(input), () => true)
console.log(output);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js" integrity="sha256-7/yoZS3548fXSRXqc/xYzjsmuW3sFKzuvOCHd06Pmps=" crossorigin="anonymous"></script>