【问题标题】:Convert string array into object with same key/value将字符串数组转换为具有相同键/值的对象
【发布时间】:2020-04-15 07:41:08
【问题描述】:

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

import stringArray from './a.js';

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

在你开始之前,我知道如何在说 constructor() 中使用 forEach、for in 循环等技巧来实现这一点。有没有简单的一行代码在类属性中而不是在函数内部实现这一点。

【问题讨论】:

  • stringArray.reduce((a, c) => (a[c] = c, a), {})
  • 您也可以使用IIFE,例如:hashmap = (() => {.. return "something"})()

标签: javascript typescript lodash


【解决方案1】:
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];
}

【讨论】:

    【解决方案2】:

    试试这个:

    const arr = ["one","two","three"]
    let obj = {}
    arr.forEach(item => {obj[item] = item})
    document.write(JSON.stringify(obj))

    【讨论】:

      【解决方案3】:

      洛达什

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

      const arr = ["one","two","three"];
      
      const obj = _.zipObject(arr, arr);
      console.log(obj);
      &lt;script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"&gt;&lt;/script&gt;

      纯 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);

      【讨论】:

      • 我试图在类成员声明中这样做,所以多行代码不起作用。但如果你改变它,我会同意你的答案
      • 什么意思?是否要将数组作为属性添加到当前实例?
      • 类 b { hashmap = _.zipObject(arr, arr); }
      • 为什么分配给什么重要?您对正确的数据感兴趣 - 无论您是生成变量还是对象属性或其他任何东西,the result is the same
      • 在这种情况下不会,但在其他多行代码情况下会。
      【解决方案4】:

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

      const arr = ["one","two","three"];
      
      const obj = _.keyBy(arr);
      
      console.log(obj);
      &lt;script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"&gt;&lt;/script&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-09
        • 1970-01-01
        • 2022-11-02
        • 2021-09-28
        • 2020-06-16
        • 2019-09-20
        相关资源
        最近更新 更多