gpt4 book ai didi

javascript - lodash json组对象成本

转载 作者:太空宇宙 更新时间:2023-11-04 15:35:04 25 4
gpt4 key购买 nike

请,我有这个 JSON 对象,想要按类型对值进行分组。

var costs = [
{ 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' },
{ 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' },
{ 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' },
{ 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' }
];

我想要这样的东西:

var costs = [
{ 'name': 'JON', 'flight':100, 'uns': 12, 'sch': 35 },
{ 'name': 'BILL', 'flight':200, 'uns': 33, 'sch': 45}
];

我尝试使用 lodash 但没有成功:

var compiled_costs = _.chain(costs)
.groupBy("flight")
.value();

{
"100":
[ {"name":"JON","flight":100,"value":12,"type":"uns"},
{"name":"JON","flight":100,"value":35,"type":"sch"}
],
"200":
[
{"name":"BILL","flight":200,"value":33,"type":"uns"},
{"name":"BILL","flight":200,"value":45,"type":"sch"}
]
}

最佳答案

var res = _.chain(costs)
.groupBy('flight') // group costs by flight
.mapValues(function(flightItems, flight) { // iterate flight arrays
return { // return obj on each flight array
name: _.get(flightItems, [0, 'name']), // just get name from first item of flight array
flight: flight,
uns: _.chain(flightItems) // get all flight items with type uns and sum items values
.filter({type: 'uns'})
.sumBy('value')
.value(),
sch: _.chain(flightItems)
.filter({type: 'sch'})
.sumBy('value')
.value()
}
})
.values() // get values from object
.value();

关于javascript - lodash json组对象成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44443095/

25 4 0
文章推荐: javascript - 在列表中的嵌套 ng-repeat 中搜索过滤器并隐藏没有 child 的 parent
文章推荐: c++ - *(vec.begin() - 1) 应该返回什么?
文章推荐: css - 使用 CSS 将 float
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com