javascript - lodash json组对象成本

标签 javascript json underscore.js lodash

请, 我有这个 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/

相关文章:

javascript - 刷新后保持折叠状态

javascript - 如何在java中检索通过ajax从javascript发送的jsonarray数据

javascript - 如何检查对象属性是否已在用户提供的参数中设置?

javascript - Functional Javascript 书籍示例中的错误

javascript - 强调某些方法给出意想不到的结果

php - $_POSTing 多个具有相同 ID 的输入,这些输入是通过 jQuery 在点击时添加的。

javascript - Extjs 3.4 删除记录后重新加载网格

javascript - 如何防止用户按退格键/后退箭头

javascript - Youtube 使用 "default"作为对象属性的名称

javascript - angularjs ng-repeat cascading Dropdown不更新