Search code examples
javascriptjsonnode-red

Node-red JSON array extracting values across large array of values


I'm building a fuel price checker page using Node-Red, building this for the family website so the kids can keep an eye on fuel costs locally vs. what the average is to try and save them some ££ when they fill up their car.

I'm trying to extract the value (or values) of an array, I usually just copy the path I need into the variable e.g.

current_price_e5 = payload.stations[0].prices.E5

Station array contains over 300 entries and from what I'm finding is dynamic in length, each with a number of keys (see image below). How can I extract all of the values for each key under prices across the array? Clearly this doesn't work but is what I need as a new msg.payload:

current_price_e5 = payload.stations[0-313].prices.E5

sample

Resolved following the code snippet suggested - For future searches the following worked for me and allowed to to get what I needed into another function to average and min/max:

const e10Prices = msg.payload.stations.map(station => 
station.prices).map(price => price.E10);
msg.payload = e10Prices;
return msg;

Solution

  • Maybe this will help you:

    const stations = [
        {
            name: "Station1",
            prices: {
                E5: 1.82,
                E10: 1.51
            }
        },{
            name: "Station2",
            prices: {
                E5: 1.76,
                E10: 1.53
            }
        },{
            name: "Station3",
            prices: {
                E5: 1.89,
                E10: 1.53
            }
        }
    ];
    
    const e5Prices = stations.map(station=>station.prices).map(price=>price.E5);
    
    console.log(e5Prices); // => [1.82, 1.76, 1.89]