The function res.map() cannot be used in this context because res is an Array Object

I am dealing with data in the following format:

[ 

{ device_id: '12335',
    timestamp: '2018-05-14T08:31:23.000Z',
    temperature: 21,
    pressure: 31,
    humidity: 20,
    equipment_name: 'truck5' },
  { device_id: '12335',
    timestamp: '2018-05-14T08:31:31.000Z',
    temperature: 28,
    pressure: 35,
    humidity: 25,
    equipment_name: 'truck5' },
  { device_id: '12335',
    timestamp: '2018-05-14T08:31:33.000Z',
    temperature: 36,
    pressure: 44,
    humidity: 33,
    equipment_name: 'truck5' },
  { device_id: '12335',
    timestamp: '2018-05-14T08:31:36.000Z',
    temperature: 31,
    pressure: 39,
    humidity: 30,
    equipment_name: 'truck5' }, 
  // additional data here...

This data is retrieved from my SQL database and stored as follows:

var res1 =[];
res1 = JSON.parse(JSON.stringify(result));

However, when I attempt to use the map function on this data, I encounter an issue:

res1.map() is not a function.

Why is this happening?

The map function should work on all array objects. It worked previously when I manually assigned the data to the variable like this res1=[{..}]. But now it's not functioning properly.

When I console.log(result) I get the following output:

[ RowDataPacket {
device_id: '12335',
timestamp: 2018-05-14T08:31:23.000Z,
temperature: 21,
pressure: 31,
humidity: 20,
equipment_name: 'truck5' },
// more data rows displayed...

To resolve this, I used JSON.stringify(). Simply using JSON.parse() resulted in an error. Below is the MySQL query function I'm utilizing:

db.query(query,
         function (err, result, fields) {
    if (err) throw err;
    var res1 =[];
    res1=JSON.parse(JSON.stringify(result));
  console.log(res1);
  series:[
                res1.map(function(s) {
                    // Meta data is necessary for tooltip plugin.
                    return {x: s.timestamp, y: s.temperature, meta: s.temperature + ' on ' + s.timestamp.toDateString()};
                })
            ]
 });

After checking the type of result or res, whether with or without JSON.parse(), I found that the type returned was object.

Answer №1

JSON.stringify and JSON.parse work in opposite directions. When you receive a JSON string from your API, it's necessary to utilize JSON.parse to convert it into a JavaScript object (such as an array).

On the contrary, using JSON.stringify may not provide much assistance in this scenario. Consider trying this approach:

var response = JSON.parse(result);
response.map( ... );

To determine the type of response you have received, you can use console.log(typeof result). If the output is string, apply JSON.parse. If it displays object, there is no need for JSON.parse.

Answer №2

The JSON data received from the server appears to be corrupted due to multiple revisions made to the original response. If the string 'x' represents the data received, here is a snippet of it:

x = 
"[ RowDataPacket {
device_id: '12335',
timestamp: 2018-05-14T08:31:23.000Z,
temperature: 21,
pressure: 31,
humidity: 20,
equipment_name: 'truck5' },

...
]
"

To correct this issue, the following script can parse the data without any errors:

JSON.parse(
    x
    .replace(/timestamp:\s*(.*),/gi,function(m,g1){return 'timestamp: "'+g1+'",'})
    ...
)

However, a more efficient solution would involve properly formatting and sending the data from the server to avoid such parsing problems in the future.

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

What's the best way to transform createHmac function from Node.js to C#?

Here's a snippet of code in Node.js: const crypto = require('crypto') const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex'); I am trying to convert t ...

What steps are involved in bundling a Node project into a single file?

Recently, I've been using npm to create projects. When it comes to AMD, I find the native node require to be very convenient and effective for my needs. Currently, I rely on grunt-watchify to run my projects by specifying an entry file and an output f ...

Error message: "Attempting to execute() on an object that is not recognized in PHP using PDO"

Currently, I am utilizing prepared statements to manage the JSON call from my cordova application to a database. My current challenge involves obtaining nearby locations based on the latitude and longitude that are being 'POST'ed, but the prepar ...

Tips for including an object in a JSON array based on the value of another key within the file using JoltTransformationJson in NiFi

I am new to using JoltTransformationJson, so my understanding and experience with it are limited. I would greatly appreciate assistance with this complex project. Request: when the payment.code <> "paid", I need to perform the following tw ...

Can you interact with a node within an Electron application even if the node integration feature is not enabled?

I have an electron app created with vanilla electron. (using npx create-electron-app ......) Can I use const electron = require("electron"); with nodeintegration:true? The library I'm using does not support nodeintegration:true, but my scr ...

Generate visual representations using Google charts and JSON data

I am looking for a way to retrieve and utilize a dataset for Google Charts from a separate JSON file. I attempted to use jQuery getJSON method but encountered issues. The goal is to have Google Viz utilize the JSON data to create a bar chart. Is there a ...

How to insert a JSON object into a nested array using JavaScript

I am currently facing an issue with adding a JSON object based on specific conditions to an array, which is then used to create a WINJSList. The problem arises when I try to access the elements of the list or array after using the array.push method. My goa ...

What is the process for transferring a file to a server and then returning it to the client?

Currently, I am working on manipulating PDF files in ReactJS and making modifications to them on the server side. However, I am facing an issue with passing my file data to the server side and then receiving it back. This is how I retrieve my file: <di ...

Having trouble with executing a MySQL update by using PDO and prepared statement

I'm facing an unusual issue with php PDO and mysql. Here is the structure of my table: create table test_table ( id integer, value text ); It contains one row: insert into test_table values (1, "asdf"); When I attempt to update this row using a p ...

Can you help me navigate through the router dom v6 to match product IDs from the API?

How do I display a specific product when it's clicked on based on its id from a Django Rest Framework API? I was previously using match from React Router DOM v5, but I'm not sure how to achieve the same functionality since match doesn't exis ...

Limiting the quantity in SimpleCart (js)

Currently, I am working on a WordPress website where I am using simpleCart(js) to add a shopping cart feature. I sell unique articles and do not require users to add more than one article to their cart. My main concern is how to prevent users from adding ...

What is the significance of including the keyword 'default' when exporting a component with withStyles?

When I create a simple React component using Mui's withStyles HOC, I find that I am required to export the component as default. Why is it not possible to use the HOC directly in the return statement of the functional component? Is there something sp ...

Calls to the function are piling up

There is a bootstrap modal that displays a confirmation message. If the 'accept' button is clicked, a function is called with an id. If the 'cancel' or 'close' button is clicked, the modal closes. The problem arises when the m ...

Retrieving a MySQL join of identical tables with matching names

I am currently working with a MySQL database. Within this database, I have two tables: Students: stud_num prof1 prof2 Professors: prof_id first_name last_name In the Students table, prof_id is utilized as a foreign key. The objective is to retrieve s ...

React Jest is experiencing an error at line 246 in the internal process promises module, triggering an uncaught exception with the specified error

In my React code snippet below, I am using the useEffect hook with an async function to fetch data: useEffect(() => { (async () => { await httpClient .get(`${config.resourceServerUrl}/inventory/`) . ...

Using XMLHttpRequest to fetch a JSON object

Having trouble with returning an object from the getMine function in Javascript? Even though you try to print out the object, it keeps showing up as undefined. How can you successfully return the obj within this function? function getMine() ...

The functionality of the submit form is encountering issues upon integration of Ajax requests

Hello everybody! I am currently creating a dynamic form for editing specific classes, but I am facing an issue with the ajax call not working. Below is the HTML code for the form: <form id="userDataForm" name="userDataForm" th:acti ...

What is the best way to configure an EmailId validator in Angular 6 to be case insensitive?

My register and login page include a form validator pattern matching for the registration form. this.registerForm = this.formBuilder.group({ firstName: ['', Validators.required], emailId: ['', [Validators.required, Validators.patt ...

Pass intricate JavaScript object to ASP.Net MVC function

It appears that many people have shared helpful answers on a common topic, but I am still facing difficulties in making my attempt work. The issue is similar to the one discussed here, however, I am only trying to send a single complex object instead of a ...

Discovering the right row to input the data and successfully integrating it: What is the best

Below is the code I am using to add a new task: <fieldset> <legend>Create New Task</legend> <input type="text" ng-model="subtaskname" placeholder="Subtask Name" ><br /> <select id="s1" ng-model="selectedItem" ng-options=" ...