gpt4 book ai didi

javascript - 在 JavaScript 中向对象添加新值

转载 作者:行者123 更新时间:2023-12-03 01:52:40 25 4
gpt4 key购买 nike

我有以下数组

array = [{
key: '2001',
values: [
{ id : '123a', points: 3, hours: 3 },
{ id : '123a', points: 4, hours: 2 },
{ id : '4444', points: 3, hours: 2 },
{ id : '4444', points: 3, hours: 5 },
]
}, {
key: '2002',
values: [
{ id : '12d3a', points: 5, hours: 2 },
{ id : '12w3a', points: 3, hours: 3 },
]
}]

有了这个功能

const {map, evolve, pipe, groupBy, prop, pluck, sum, toPairs, zipObj} = R;

const a = map(evolve({
values: pipe(
groupBy(prop('id')),
map(pluck('hours')),
map(sum),
toPairs,
map(zipObj(['id', 'hours']))
)
}))

我收集了每个键的每个 id 的所有“小时”(2001、2002..)

array = [{
key: '2001',
values: [
{ id : '123a', hours: 5 },
{ id : '4444', hours: 7 }....

现在我想为每个对象添加另一个值,称为 sum。var sum = (点数*小时)/(总和(小时))。

知道我该怎么做吗?我尝试更改 const a 但不起作用,我不知道 ramda 是否可以执行此操作。也许有替代方案?

array = [{
key: '2001',
values: [
{ id : '123a', hours: 5, sum: 3.4 },
{ id : '4444', hours: 7, sum: 3 }....

最佳答案

这是一个 Ramda 版本,它的工作原理是简化为包含 id、总小时数和总积分的中间结构,然后转换为最终格式:

const {map, evolve, pipe, groupBy, prop, reduce, values} = R;

const array = [{"key": "2001", "values": [{"hours": 3, "id": "123a", "points": 3}, {"hours": 2, "id": "123a", "points": 4}, {"hours": 2, "id": "4444", "points": 3}, {"hours": 5, "id": "4444", "points": 3}]}, {"key": "2002", "values": [{"hours": 2, "id": "12d3a", "points": 5}, {"hours": 3, "id": "12w3a", "points": 3}]}]

const a = map(evolve({
values: pipe(
groupBy(prop('id')),
map(reduce(
({tp, th}, {id, points, hours}) => ({id, tp: tp + points * hours, th: th + hours})
, {tp: 0, th: 0}
)),
values,
map(({id, th, tp}) => ({id, hours: th, sum: tp/th})),
)
}))

console.log(a(array))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

关于javascript - 在 JavaScript 中向对象添加新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50350131/

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