"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

Bringing in a selection of functions as an object using ES6 imports

functions.js export const setA = () => {...} export const setB = () => {...} export const setC = () => {...} component.js import {setA, setB, setC} from 'functions' export class componentOne extends React.Component { constructor(p ...

What is the best way to modify the values in an initialized array once the fetchData method has been executed?

As a beginner in Vue.js, I am currently working on a project that involves updating initialized arrays in the data() section of my component using the fetchData method. Below is a simplified version of the code: <script> import axios from 'axi ...

Display HTML content repeatedly depending on the number selected in a dropdown menu using AngularJS

I need your assistance with a dropdown selection feature on my website. The idea is that based on the number chosen from the dropdown, I want to dynamically repeat sections in HTML. For example, if I select 3 from the dropdown menu, the page should display ...

When navigating to a new route using history.push in React, it's important to ensure that the correct state is

My goal is to implement a smooth exiting animation with framer motion based on the user's current route and next destination. I specifically want the background to slide away only when transitioning from route A to route D. To achieve this, I decided ...

Use Jquery to add unique styles to specific words within a paragraph

I am looking to specifically style a particular word within a dynamic div for example, <div id="info">{$info}</div> prints <p>here you can get info about somnething. if you want more info about something then click here....</p> ...

Facing an infinite loop issue with my ng-view and the index.html page in AngularJS

Hello everyone, I have a question regarding AngularJS ngview. I just started learning about Angular a week ago. In my code, the webpage is showing an infinite loop of the index itself instead of displaying the correct page. I've searched on Stack Ove ...

Performing AJAX requests within AJAX requests without specifying a callback function for success

Upon reviewing this discussion jQuery Ajax Request inside Ajax Request Hello everyone, I'm in need of some clarification on a particular scenario. I recently took over the code from a former member of my development team and noticed that they have ma ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Separate modules in the Webpack.mix.js file don't produce any output files in the public folder

I've recently been tackling a Laravel project with an extensive webpack.mix.js file residing in the root directory, boasting nearly 5000 lines of code. In an effort to enhance organization and maintainability, I've opted to break it down into ind ...

Issue with displaying content using v-show in a Nuxt.js menu

Struggling to create a mobile menu with Vue instance error The Nuxt Menu Component : <template> <header id="menu" class="menu-g"> <Nuxt-link to="/"><img src="~assets/logo.svg" alt=&qu ...

The issue in AngularJS 1.4 where the select element value is not binding due to a type mismatch

My ng-model has a value assigned to it, but it is not binding with the selected element. <select data-ng-model="myval"> <option value="? number:2 ?"></option> <option value="2" class="ng-binding">Value 1</option> <op ...

Get the package from a Lerna-managed monorepository using a git URL

Currently working on a project using yarn. The project has a dependency that is part of a larger monorepo managed by lerna. Despite the subpackage being updated, it has not been published yet and I require access to that unreleased code. Is there a method ...

How to implement PayPal integration in PHP

I am currently working on integrating the paypal payment system into a website dedicated to pet adoption. Initially, I had a basic code structure that was functional. However, after making some modifications and additions to the code, it no longer redirect ...

Implementing a JQuery modal with backend coding

I have encountered a problem in my ASP.NET code-behind where I am trying to incorporate a modal popup. Despite my efforts, I have not been able to successfully implement it. Do you have any suggestions on how I should proceed with this process? <scrip ...

javascript making a button using an object

When trying to create a button from a JavaScript object, I am following this approach: for (buttonName in buttons){ var htmlbutton = '<button type="button" onclick="'+buttons[buttonName]()+'">'+buttonName+'< ...

Is it possible to pass a parameter to a PHP controller using JavaScript without relying on jQuery or AJAX?

Is it possible to achieve the task at hand? That's the main question here. My goal is to extract data from a popup window and then, upon closing it, send this extracted content to a PHP controller for further processing. I'm facing conflicts wi ...

What could be causing webpack to struggle in locating the loader?

Check out my package.json: { "name": "redux-todo", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "webpack-dev-server" }, "devDependencies": { "babel": "^6.5.2", "babel-loader": "^6.2.5", "bab ...

Start the Express server by utilizing Grunt

Can anyone assist me with adding a task to my Gruntfile that will start my Express server instead of the default one? I attempted to create a task and use require("server.js"), but it doesn't seem to be working properly. When I run "grunt mytask", the ...

Encountered a SyntaxError on JSON Web Tokens Node JS Server: Unexpected token } found in JSON at position 24

Me, along with others, have encountered this issue: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following a tutorial on JSON Web Tokens (TUTORIAL LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s ...

Contact form repair completed - Messages successfully delivered

I am facing an issue with the contact form on my HTML landing page. Currently, when you click the 'Submit' button, it redirects to a new PHP page displaying 'Success'. Is there a way to make it so that upon clicking 'Submit' a ...