将字符串数组转换为具有相同键/值的对象

时间:2020-04-15 07:41:08

标签: javascript typescript lodash

如何将["one","two","three"]转换为{one:"one", two:"two", three:"three"}

import stringArray from './a.js';

class b {
 hashmap = stringArray// convert this into Object here inline.
}

在您跳楼之前,我知道如何使用诸如forEach,for in in等之类的技巧在构造函数()中实现此功能。是否有简单的一行代码就可以在类属性中而不是在函数内部实现此功能。 >

4 个答案:

答案 0 :(得分:0)

请尝试这样

const arr =["one","two","three"]

let obj ={}
arr.forEach(item=> obj[item] = item)

答案 1 :(得分:0)

Lodash

您可以使用_.zipObject。它接受两个数组-一个用于键,另一个用于值,但是如果您只使用两次相同的数组,则会得到匹配对:

const arr = ["one","two","three"];

const obj = _.zipObject(arr, arr);
console.log(obj);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

普通JavaScript

您可以使用Object.fromEntries做同样的事情。它可以与一组键值对配合使用,因此您必须将其转换为:

const arr = ["one","two","three"];

const matchingKeyValuePairs = arr.map(x => [x, x]);

const obj = Object.fromEntries(matchingKeyValuePairs);
console.log(obj);

您还可以使用Array#reduce生成具有计算出的属性名称的对象:

const arr = ["one","two","three"];

const obj = arr.reduce((acc, item) => ({...acc, [item]: item}), {});
console.log(obj);

答案 2 :(得分:0)

data = ["one","two","three"];
data = data.map(e => [e,e]) // keyvalue pairs [["one","one"],["two","two"],["three","three"]]
data = Object.fromEntries(data); // {"one":"one","two":"two","three":"three"}

map会将输入数组的每个元素转换为所需的结构。

在这种情况下,我们希望将每个元素转换为一个数组,并在其中重复两次元素

Object.froEntries会将键值对列表转换为Object

这也可以使用普通的for循环

完成
data = ["one","two","three"];
obj = {};
for(let i = 0; i < data.length ; i++){
   obj[data[i]] = data[i];
}

答案 3 :(得分:0)

Lodash具有_.keyBy()函数,该函数通过提供的函数(迭代器)根据值生成键,从而从数组创建对象。默认的iteratee是_.identity(),它返回值。

const arr = ["one","two","three"];

const obj = _.keyBy(arr);

console.log(obj);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>