"Transforming JSON data into structured key-value pairs using JavaScript

Develop a function named "json_filter" that accepts a JSON-formatted string as input. The accepted format is an array of objects, where each object contains keys for "mass," "density," "temperature," and "velocity," each mapped to a floating-point number. This function should output the input as a JSON string in the same format but only include objects with a temperature greater than 31.92.

function json_filter(format){

  var array = JSON.stringify(format);
  var filteredArray = [];

  for (var i = 0; i < array.length; i++){
      if (array[i].temperature > 31.92){
         filteredArray.push(array[i]);       
      }  
  }
  
  return JSON.parse(filteredArray);

}

Upon running this code, an error message might appear like the one below:

Error while processing input ['[{"velocity": 11.33, "mass": 14.56, "density": 165.09, "temperature": 29.92}, {"velocity": 57.86, "mass": 52.23, "density": 770.6, "temperature": 35.61}, {"velocity": 62.23, "mass": 84.85, "density": 85.22, "temperature": 51.66}, {"velocity": 16.63, "mass": 51.23, "density": 995.61, "temperature": 10.27}, {"velocity": 31.16, "mass": 71.76, "density": 967.53, "temperature": 50.43}, {"velocity": 14.35, "mass": 0.92, "density": 808.42, "temperature": 69.32}, {"velocity": 85.43, "mass": 41.07, "density": 899.84...]: TypeError: Cannot read property 'temperature' of undefined

If you encounter this issue or need help correcting it, feel free to ask for assistance.

Answer №1

function filterJsonData(data){

  var jsonData=JSON.parse(data);
  var filteredData = [];

  for (var j = 0; j<jsonData.length;j++){
     if (jsonData[j]["temperature"]>31.92){
        filteredData.push(jsonData[j]);
     }
  }
  return JSON.stringify(filteredData);
}

(answered the question as shown above, but unable to mark it answered because I'm a new member and need to wait for 2 more days.)

Answer №2

Give this a try.

function filterJSONData(format){
  let array = JSON.parse(format);
  return JSON.stringify(array.filter(obj=>obj.temperature>31.92));
}

In case you are unable to utilize es6, use the following:

let filterJSONData = function(format){
  let array = JSON.parse(format);
  return JSON.stringify(array.filter({temperature}=>temperature>31.92));
}

If you have access to es6, go for the second option. Keep in mind that the first solution will also work with es6 but not vice versa.

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

Creating a singular and distinctive string by combining two keywords

Is it possible to create a single distinct string by combining two keywords regardless of the order in which they are entered? EDIT: The keywords in question are numerical rather than alphabetical characters. The following example is merely for explanator ...

Guide on displaying a real-time "Last Refreshed" message on a webpage that automatically updates to show the time passed since the last API request

Hey all, I recently started my journey into web development and I'm working on a feature to display "Last Refreshed ago" on the webpage. I came across this website which inspired me. What I aim to achieve is to show text like "Last Refreshed 1 sec ago ...

Having difficulty creating the probot.github app due to an error: The removal of the programmatic API in npm version 8.0.0 causing failure

Currently, I am facing an issue while attempting to set up the probot.github app using the command npx create-probot-app my-first-app which can be found at: . My system is running on the latest node version v19.3.0 with npm version 9.2.0. However, upon exe ...

What is the best way to handle form data for JSON manipulation in jQuery?

var checkedValues = $('.required:checked').map(function () { return this.value; }).get(); var arr = new Array(10); alert(checkedValues); alert("number of values in it " +checkedValu ...

Deactivate a <tr> element if any of its <td> cells contain a value

In my table, there are various trs and tds with different element names. I need to determine if there is text in a specific field. If there is text, I want to disable or hide the entire tr to prevent user interaction. Unfortunately, I am unable to provide ...

Error: Unable to instantiate a THREE.Scene object in Three.js due to TypeError

Recently, I decided to experiment with Three.js in order to incorporate it into a project of mine. However, upon running the initial example provided in the documentation: <html> <head> <title>My first Three.js app</title& ...

What is the best way to update the content of a div on an HTML page by incorporating the content of a div from a different page using JavaScript?

I have a requirement where I need to implement a link in a Table of Contents that, upon clicking, should replace the existing content of one div on a page with the content of another div on a different page. My goal is to accomplish this using only JavaScr ...

Is async programming synonymous with multi-threading?

Discussing a JavaScript code that utilizes the setInterval function every 2 seconds. There is also an animation event for some control triggered by the onblur event. If the onblur event occurs (along with the animation), there is a possibility of encount ...

"Encountering an Issue with Storing Private Key as a String in NodeJS: Saving to .txt Results in Writing "[

Currently, I am attempting to save an EC key pair from the elliptic library as a string in a .txt file. However, when I do this, it ends up writing ""[object Object]"" to the file. UPDATE: Just wanted to note that the issue of turning the object ...

Embed a subcomponent within another component triggered by an onClick event in ReactJS

Watch this quick demo to see my project in action. So, here's the deal - I have a menu with different options, and when "Tickers" is selected, I want it to display the Tabs component. However, if any other menu option is chosen, I don't want the ...

Embed a website in an iframe and modify a portion of the URL within the embedded page

Welcome to my first question here! I am looking for a solution that will allow me to load a webpage inside an iframe while modifying parts of the URLs in any links on the page with different text. For example, let's say we load a website like "myweb ...

Cypress - A Guide to Efficiently Waiting for the Outcome of a Javascript Function Import

I am interested in creating a Javascript library to act as a wrapper for 3rd party APIs. I have decided to write the API wrapper as a standalone file rather than using Cypress Custom functions, so that I can share the library with teams who are not using C ...

updating information automatically on page every X seconds for Angular component

I am trying to implement a way to automatically refresh the data of an Angular component every 30 seconds. Currently, I have used a simple setInterval function like this: this.interval = setInterval(() => { this.refresh(); // api call ...

Angular model is not receiving the value of a false checkbox

One issue I am facing is with a form that includes a checkbox bound to an ng-model property. The problem arises when the checkbox is checked, as the value gets set in the model. However, when it is unchecked, the key and value remain unset, causing API val ...

PHP unable to display HTML form element using its designated ID attribute

I've been experiencing some difficulties with PHP echoing a label element that contains an ID attribute within an HTML form. My intention was to utilize the ID attribute in order to avoid having to modify the JS code to use the name attribute instead. ...

a function that repeats every single second

A challenge I am facing is creating a countdown timer with a time that refreshes every second. My current implementation uses setInterval, but it only seems to run once instead of every second. Can anyone help me identify the issue in my code? var countDo ...

Increasing several array elements within a MongoDB object

I have been struggling with this problem for some time now. My goal is to update multiple array values in the same object with a single query. The data in the database appears as follows: id: 616f5aca5f60da8bb5870e36 title: "title" recommendations: ...

Exploring the possibilities of integrating Storybook/vue with SCSS

After creating a project with vue create and installing Storybook, everything was running smoothly. However, as soon as I added SCSS to one of the components, I encountered the following error: Module parse failed: Unexpected token (14:0) File was process ...

How to Remove onFocus Warning in React TypeScript with Clear Input Type="number" and Start without a Default Value

Is there a way to either clear an HTML input field of a previous set number when onFocus is triggered or start with an empty field? When salary: null is set in the constructor, a warning appears on page load: Warning: The value prop on input should not ...

Error: The property 'json' is undefined and cannot be read. Please handle this promise rejection

answers.forEach((answer, index) => { answer_text = answer.answer_text; id = answer.id; fetch(BASE_URL + url, { method: 'PUT', headers: { 'Accept': 'application/json', 'Content-Type': &apo ...