gpt4 book ai didi

javascript - 如何在 loDash 函数中使用变量

转载 作者:行者123 更新时间:2023-11-28 03:07:22 24 4
gpt4 key购买 nike

美好的一天,

这是我的数据架构:

数据长度可能会根据查询而变化

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 函数中的变量?

感谢您的帮助。

问候

最佳答案

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

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

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)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

还有稍微干净一点的 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)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

关于javascript - 如何在 loDash 函数中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60484619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com