如何将数据中Pressure相关字段分别存入对应独立数组?
Got it, let's sort this out for you. The issue with your current code is that you're pushing both Pressure and Pressure2 values into the same pipelines.data array, which is why you're getting double the values. Plus, your map attempts were likely failing due to incorrect usage (like not returning values or targeting the wrong part of the data).
Here are two solid approaches to fix this:
1. Explicitly Target Known Pressure Fields (Simple & Direct)
If you know exactly which pressure fields you need (like Pressure and Pressure2), initialize separate arrays for each and populate them in your loop:
// First, set up your pipelines object with empty arrays const pipelines = { pressure: [], pressure2: [], creationDate: [] }; // Loop through each row to populate the arrays this.query.rows.forEach(row => { const rowData = row.data; pipelines.pressure.push(rowData.Pressure); pipelines.pressure2.push(rowData.Pressure2); pipelines.creationDate.push(row.creationDate); });
2. Dynamic Approach (Handle Any Pressure-Named Fields)
Since you already have the keys from data, you can use them to dynamically create and populate arrays for any field that includes "Pressure"—this is great if you might add more pressure-related fields later.
// Initialize base pipelines structure const pipelines = { creationDate: [] }; // Get all data keys and filter for ones containing "Pressure" const myDataKeys = Object.keys(this.query.rows[0].data); const pressureKeys = myDataKeys.filter(key => key.includes('Pressure')); // Create empty arrays for each pressure key (convert to lowercase for consistency if you want) pressureKeys.forEach(key => { pipelines[key.toLowerCase()] = []; // Result: pipelines.pressure, pipelines.pressure2, etc. }); // Populate all arrays by looping through rows this.query.rows.forEach(row => { // Add creation date pipelines.creationDate.push(row.creationDate); // Add values to each pressure array pressureKeys.forEach(key => { pipelines[key.toLowerCase()].push(row.data[key]); }); });
Fixing Your Map Function Issues
If you wanted to use map instead of forEach, here's how to do it correctly (no undefined results!):
// Use map to extract each field's values directly const pressureArray = this.query.rows.map(row => row.data.Pressure); const pressure2Array = this.query.rows.map(row => row.data.Pressure2); const creationDateArray = this.query.rows.map(row => row.creationDate); // Combine into your pipelines object const pipelines = { pressure: pressureArray, pressure2: pressure2Array, creationDate: creationDateArray };
The reason you were getting undefined before is probably because your map callback wasn't returning a value, or you were looping over object keys instead of the rows themselves. This approach directly maps each row to the value you need, so it works reliably.
内容的提问来源于stack exchange,提问作者Baub

