Querying data from a vast JSON array using Node-RED to extract specific values

I'm working on a fuel price monitoring feature for our family website using Node-Red. This tool is aimed at helping the kids keep track of local fuel prices compared to the average, in an effort to save some money when they refuel their cars.

Currently, I am attempting to extract the values from an array by copying the necessary path into a variable like so:

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

The 'stations' array consists of over 300 entries and appears to be dynamic in terms of length, each entry containing multiple keys (refer to image below). How can I retrieve all the values for each key under 'prices' across the entire array? The approach mentioned above clearly doesn't work, but it is what I require for a new msg.payload:

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

https://i.sstatic.net/M0VhZ.jpg

Fortunately, I was able to resolve this issue by following the suggested code snippet. For future reference, the following code worked for me and allowed me to further process the data for averaging, minimum, and maximum calculations:

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

Answer №1

Perhaps this solution could be of assistance:

const fuelStations = [
    {
        name: "Gas Station A",
        prices: {
            Regular: 2.30,
            Premium: 2.60
        }
    },{
        name: "Gas Station B",
        prices: {
            Regular: 2.15,
            Premium: 2.45
        }
    },{
        name: "Gas Station C",
        prices: {
            Regular: 2.40,
            Premium: 2.70
        }
    }
];

const regularPrices = fuelStations.map(station=>station.prices).map(price=>price.Regular);

console.log(regularPrices); // => [2.30, 2.15, 2.40]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

The default locale for momentJS is set to zh-tw and I'm having trouble changing it

Currently, I am incorporating the momentJS library into my Angular application by pulling it from a CDN: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script> Although the default locale should be Engli ...

Convert a JSON string into an object by extracting data from 3 specific properties

Let's say I have a JSON with 3 objects and their values { "SomeProperty": "42", "Foo": "bar", "Name001": "ABC_1", "Type001": "D", "Confidence001": "100", ... "Name00N": "ABC_N", "Type00N": "D", "Confidence00N": "50 ...

Securing client-side code with AngularJS for enhanced security

It's a known fact that once browsers have downloaded frontend files, there's no way to hide code from the client. However, I've heard that clients can debug JavaScript code, add breakpoints, skip code lines (especially security checks), and ...

Move the modal dialog so it appears closer to the top of the page

I am facing a challenge with my jQuery modal dialog. While it is loading properly, I am restricted to using an older version of jQuery (1.12.4) and cannot upgrade it. My goal is to center the modal close to the top of the page, similar to how it is positio ...

Is there a way to implement jquery (or other external libraries) within Typescript?

Currently, I am diving into Typescript to enhance my skills and knowledge. For a project that is being served with Flask and edited in VSCode, I am looking to convert the existing JavaScript code to Typescript. The main reason for this switch is to leverag ...

JavaScript array reformatting executed

I have an array object structured like this. [ {student_code: "BBB-002-XRqt", questions: "Length (in inches)", answer: "8953746", time: "00:00:08:15"}, {student_code: "CCC-003-TYr9", questions: "He ...

Every time I attempt to launch my Discord bot, I encounter an error message stating "ReferenceError: client is not defined." This issue is preventing my bot from starting up successfully

My setup includes the following code: const fs = require('fs'); client.commands = a new Discord Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js')); for(const file of com ...

"How can I exclude empty fields from the form.serialize function in jQuery when using php?" is not functioning as expected

I am facing an issue with using How do I use jQuery's form.serialize but exclude empty fields. Despite following a minimal example that directs to a php script: <html><head> <script src="jquery.min.js"></script> <script typ ...

JavaScript preloader failing to wait for images to load

I came across this Javascript code to enable the pre-loader on my website. However, I noticed that it disappears as soon as the page loads, instead of waiting for all images to finish loading. After some research, I found a suggestion to use window.onload ...

Navigate back to the previous route within the Vue router hierarchy

In my Vue application, I have a Settings page with child routes such as settings/user, settings/addUser, etc. I am looking to implement a back button that when pressed, takes the user back to the specific page they visited within the Settings section. Usin ...

"Creating a dynamic loop in jQuery using JSON data fetched through an AJAX call to

I am a newcomer to Javascript and I am working on a jQuery-ajax-php project that seems to be exhibiting some strange behavior. The functionality works, but only sometimes. Here is my desired sequence of actions: Set up form settings (works) Retrieve JSO ...

The 'url' parameter has been deemed valid, yet the response from the upstream is deemed invalid

For my next js project, I am utilizing the Remotive API ( ) which provides a URL to the company logo. Here is how I am using it: <Image src={'https://remotive.com/job/1912073/logo'} className="w-6 aspect-sq ...

The c++ bson extension failed to load, so the pure JS version is being utilized while using monk for Mongodb access

Whenever I try to utilize monk as a middleware for accessing mongodb, I keep getting the following message: Unable to load the c++ bson extension, resorting to pure JS version Here are the specifics of my environment: Operating System: OS X Yosemite No ...

Delegate the custom deserializer in Jackson back to the default one

Is there a strategy in a custom Jackson deserializer to hand over certain properties to the default deserializer for processing? @Override public final T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ...

Centered iframe within a div

I am trying to center my iframe within a white box and need some assistance with this. I want the iframe to be in the middle of the white box rather than its current position at the moment. game1.html: <html> <head> <title>R ...

Issue with resetting the state of a react-select component remains unresolved

I'm currently facing two issues with my react-select component: Firstly, once I select an option, I am unable to change it afterwards. Second, when my form is reset, the react-select component does not reset along with the other fields. For simplici ...

Looking to update model data in SAPUI5 by triggering a switch action?

I'm trying to figure out how to update model data when a switch button is pressed. Specifically, I want the model to change to JSON if the state is true, and ODATA if it's false. Any tips on how to tackle this problem would be greatly appreciated ...

Utilizing Azure Logic Apps to dispatch a JSON message onto ServiceBus

I am having difficulty sending JSON to Azure ServiceBus from a Logic App due to formatting issues. The Logic App retrieves data from a SharePoint Online list item as dynamic content, which I can access within the Logic App. Assume the JSON template is stru ...

What modifications are needed to transform an input[type=text] element into a textarea?

Is there a way to make an input[type=text] element behave like a textarea, displaying multiple lines and having a larger height? Unfortunately, I cannot simply replace it with a textarea. Any suggestions on how to convert or modify the input element to w ...