使用ramda.js获取嵌套对象数组中键的所有值 [英] Get all values of a key in a nested array of objects using ramda.js

查看:364
本文介绍了使用ramda.js获取嵌套对象数组中键的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何使用ramda继续这种情况感到有些困惑。这是我正在使用的JSON。

I am a little confused in how to proceed with this scenario using ramda. Here is the JSON that I am working with.

{
type:CartWsDTO,

Cartentries:[{
entryNumber:1,
flightGroup:{
PAXDetails:[{
paxID:1,
paxPrice:770.82,
paxType:ADT
},{
paxID:2,
paxPrice:770.82 ,
paxType:ADT
}]
}
},{
entryNumber:2,
flightGroup:{
PAXDetails:[{
paxID:1,
paxName:Vinitha,
paxPrice:770.82,
paxSurname:Vinitha,
paxType:ADT
},{
paxID:2,
paxName:Prahal,
paxPrice:770.82,
paxSurname:Prahal,
paxType:ADT
}
}
}]
}

上述JSON中有2个CartEnteries。每个条目的flightGroup中都有一个名为paxDetails的数组。从这个paxDetails数组我想选择paxPrice并为该购物车条目的所有pax价格总和。在传统的for循环中,如果条件我能够实现它。但是使用Ramda我无法理解如何开始。请给我一个解决方案。

There are 2 CartEnteries in the above JSON. There is an array named paxDetails in flightGroup of each entry. From this paxDetails array I want to pick the paxPrice and make a sum of all the pax prices for that cart entry. In traditional for loop and if conditions I am able to achieve it. But using Ramda I couldn't understand how to start with. Kindly provide me a solution.

提前致谢。

推荐答案

我不太清楚你在寻找什么作为输出。这是一个简单地返回两组价格之和的解决方案,并返回一个包含这些值的数组:

It's not entirely clear to me what you're looking for as output. Here's a solution that simply returns the sum of the two sets of prices and returns an array with those values:

var calcTotals = R.pipe(
    R.prop('Cartentries'),
    R.map(R.pipe(
        R.path(['flightGroup', 'PAXDetails']),
        R.map(R.pipe(R.prop('paxPrice'), Number)),
        R.sum
    ))
);
calcTotals(cart); //=> [1541.64, 1541.64]

但是如果你想要一种不同的输出,例如

But if you wanted a different sort of output, such as

{1: 1541.64, 2: 1541.64}

[{entryNumber : 1, total: 1541.64}, {entryNumber: 2. total: 1541.64}]

或者其他什么,你必须做一些改变。

or whatever, you'd have to make some changes.

这篇关于使用ramda.js获取嵌套对象数组中键的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆