在Lodash中将字符串数组转换为哈希映射表

5
什么是从这个状态精确转换的最佳方式?
["access","edit","delete"]

转换为:

{access:true, edit:true, update:true}

目前我需要循环遍历对象为每个值赋值,但我想知道lodash是否已提供此功能。

4个回答

5
使用reduce()。这可以通过一个简单的一行代码完成,不需要任何库:

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}), {})
);


3

LODASH

您可以将其映射到条目数组,然后简单地使用lodashfromPairs方法。

_.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]))

2

不需要为如此简单的事情导入库,只需将键数组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);


1
如果你绝对想使用lodash(而不是上面的纯javascript reduce()答案),你可以使用_.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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接