【问题标题】:how to use a variable in a loDash function如何在 loDash 函数中使用变量
【发布时间】:2020-06-14 11:59:25
【问题描述】:

早安,

这是我的数据架构:

数据的长度可以根据查询而改变

var data = {
IP1: 1,2,3,4,5,6
IP2: 4,5,6,7,8,9
IP3: 1,7,8,5,9,6,3}

keys=Object.keys(data)

sum=[]
for (i=0;i<keys.length;i++){
k='o.'+keys[i]

sum.push(_.sumBy(data, function(o) { return k }))
}

我正在研究 Skywise/palantir,有时我需要使用 loDash sumBy 函数对所有列求和

我的问题:有没有一种方法可以让 o.key[i] 作为 lodash 函数中的变量?

感谢您的帮助。

问候

【问题讨论】:

  • 你的问题现在不是很清楚。就像@ShahadatHossain 提到的那样,首先开始: - 描述您想要操作的对象 - 然后描述您想要实现的目标。这有 2 件事: - 为您的数据提供上下文和可见性 - 让人们了解您想要实现的目标。
  • 我期待 dataSys 变量包含的样本数据。

标签: javascript lodash


【解决方案1】:

如果我理解正确,您正在尝试获取列的总和(例如 1、4、1)。

您可以使用 lodash 创建一个带有 _.flow() 的函数,该函数获取对象(数组)的值,使用 _.unzip() 将它们转置(行到列),然后通过将每一列与 @ 映射来求和987654323@:

const { flow, values, unzip, map, sum } = _ 

const fn = flow(
  values, // get the values of the object - a list of arrays 
  unzip, // unzip to transpose the arrays to columns
  arrs => map(arrs, sum) // sum each column
)

const data = {
  IP1: [1, 2, 3, 4, 5, 6],
  IP2: [4, 5, 6, 7, 8, 9],
  IP3: [1, 7, 8, 5, 9, 6, 3]
}

const result = fn(data)

console.log(result)
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"&gt;&lt;/script&gt;

还有更简洁的 lodash/fp 版本:

const { flow, values, unzip, map, sum } = _ 

const fn = flow(
  values, // get the values of the object - a list of arrays 
  unzip, // unzip to transpose the arrays to columns
  map(sum) // sum each column
)

const data = {
  IP1: [1, 2, 3, 4, 5, 6],
  IP2: [4, 5, 6, 7, 8, 9],
  IP3: [1, 7, 8, 5, 9, 6, 3]
}

const result = fn(data)

console.log(result)
&lt;script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 2020-12-05
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    相关资源
    最近更新 更多