【问题标题】:How can I generate a key pairing object result with lodash?如何使用 lodash 生成密钥配对对象结果?
【发布时间】:2018-11-09 20:30:46
【问题描述】:

我有以下数组:

const ids = ["1234", "5678", "0987", "6543"]

我需要一个带有 lodash 的函数来返回:

const result = {"1234": { workId: null }, "5678": { workId: null }, "0987": { workId: null }, "6543": { workId: null }}

lodash 方法的使用方式是什么?

感谢您的帮助

【问题讨论】:

  • 为什么需要使用lodash?您可以使用普通的forEach 轻松完成此操作
  • const result = {}; for (const id of ids) { result[id] = {workId: null}; }
  • ids.reduce((a, k) => ({...a, [k]: { workId: null } }), {}) ???

标签: javascript arrays object functional-programming lodash


【解决方案1】:

这是一个使用 lodash#invertlodash#mapValues 的 lodash 解决方案

const result = _(ids)
  .invert()
  .mapValues(() => ({ workId: null }))
  .value();

const ids = ["1234", "5678", "0987", "6543"];

const result = _(ids)
  .invert()
  .mapValues(() => ({ workId: null }))
  .value();
  
console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

【讨论】:

    【解决方案2】:

    免责声明:lodash 对此太过分了。

    您可以使用reduce (link to doc)... 或其plain JS equivalent

    const ids = ["1234", "5678", "0987", "6543"]
    console.log(ids.reduce((acc, key) => Object.assign(acc, { [key]: { workId: null } }), {}));

    请注意,我使用 ES2015 的一个特性来动态设置要添加到累加器的新密钥的名称。

    【讨论】:

      猜你喜欢
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      相关资源
      最近更新 更多