Get all values of a key in a nested array of objects using ramda.js

妖精的绣舞 提交于 2020-01-02 22:03:14

问题


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" } ] } } ] }

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.

Thanks in advance.


回答1:


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}

or

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

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



来源:https://stackoverflow.com/questions/34314769/get-all-values-of-a-key-in-a-nested-array-of-objects-using-ramda-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!