Tips for accessing JSON values in JavaScript

How can I extract values from a JSON object in JavaScript? Below is the code snippet I've tried:

var obj={"0.5":0.009333, "0.21":0.048667,"0.31":0.070667};
    var value =0.21;
    var p=0;
    for(i=0; i<= obj.length ;i++){
    if(value== obj[i]){                         
           p = obj[i];                   //I'm expecting p to be 0.048667
           console.log("psr is :"+p);
        }
    }

Answer №1

Hmm... could simply using obj[value] get the job done? :)

Answer №2

JavaScript does not support the use of obj.length. To loop over it, you will need to utilize the following method:

for(var index in object) {
    var p = object[index];
    console.log(p);
}

If you already know the key, then you can simply do:

console.log(object[key]);

Here is the full code snippet:

var obj = {"0.5":0.009333, "0.21":0.048667,"0.31":0.070667};
var value = "0.21";
var p = obj[value];
console.log(p);

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

Designing dynamic SVG elements that maintain uniform stroke widths and rounded edges

I'm currently tackling a project that involves creating SVG shapes with strokes that adjust responsively to the size of their parent container. My aim is for these shapes to consistently fill the width and height of the parent container, and I intend ...

Combining outcomes from two separate jQuery AJAX requests and implementing deferred/promise functionality

I am struggling to combine the outcomes of two jQuery AJAX requests. Despite reviewing similar questions here, none seem to provide a solution. Each ajax call (2 in total) has a success function that calls the createStatusView function and passes it the ...

The direction to the Excel document for conversion into JSON

I have a project in progress where I'm currently working on converting an Excel sheet to JSON. Once the data is converted, it will be displayed using jQuery Datatables on the browser. My code is functioning as expected, but I am encountering an issue ...

Refresh a div with Ajax once all data has been fully loaded

I am currently using an ajax refresh div function that reloads a specific div every 10 seconds. Occasionally, the div loads before receiving data from mysql. Is there a way to modify it so that it waits 2 seconds after reloading the div? <script type ...

Storing raw HTML in a Mysql database, then fetching and displaying it on a webpage

I'm having an issue with my application. It's a form builder that allows users to create their own forms and then save them for later use. The HTML code generated by the form builder is stored in a MySQL database. However, when I try to retrieve ...

The issue encountered is: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]. The specific subpath 'lib/sync' within the package is not properly defined by the "exports" section in the package.json file located in the node_modules/csv-parse

Every time I execute index.js in Node.js, I encounter this error message. Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/sync' is not defined by "exports" in D:\Scuola\5f_Informatca\Tpsit\Telegram\node_modu ...

Retrieving JSON data from AngularJS in Flask

I am facing an issue with my AngularJS app. It sends data using HTTP PUT to a flask server, and while the data reaches the server correctly, the flask method is unable to read it when the HTTP PUT request is made by Angular... Flask code: @app.route(&apo ...

Having Trouble with Finding Visible Divs?

Below is the code snippet I am working with: var len = $(".per:visible").length; $("#add-person").click(function(){ if ($(".persons div:visible").next().is(':hidden')){ $(".persons div:visible").next().slideDown('slow' , ...

Leveraging JavaScript and Thymeleaf to manipulate a list

I am trying to access an object from a list in JavaScript, which is being passed from the controller. Currently, I am working with Thymeleaf and Spring Boot. The list is named ${collaborateurs}. The following code snippet is functional: <script th: ...

Transform the componentDidUpdate method that uses prevProps into a custom hook integrated with Redux

Trying to convert a life cycle method into a hook is not working as expected. When the component mounted, if the user ID exists in local storage, the user is connected and their name is displayed in the navbar. If they disconnect and reconnect, their name ...

Issue encountered while retrieving a JSON response from the http request

Attempting to retrieve the response from an http request through the Hunter API. The URL resembles the following: https://api.hunter.io/v2/email-finder?domain=mydomain&api_key=myapikey&first_name=myfirstname&last_name=myname The response see ...

Developing a innovative and interactive nested slider using Jssor technology

Trying to implement a dynamic jssor nested slider to showcase albums and images from a mySQL database. Everything works fine with a single album, but when there are two or more albums, the display gets messed up. I'm still learning JavaScript and JQue ...

The Select2 ajax process runs twice

I am encountering an issue with a script I have that retrieves data from the backend to populate a select2 dropdown. The problem is that the ajax call is being triggered twice every time, which is not the desired behavior. I'm unsure of what mistake I ...

Adding an id to a ul tag using JavaScript

I am trying to dynamically add an ID called "myMenu" using JavaScript to a ul element for a search filter. Unfortunately, I am unable to directly access the ul tag to change it, so I need to do it via JavaScript. As I am new to JavaScript, I am looking t ...

Creating a JSON Schema using a Java object

Is there a way to generate JSON schema from Java Class using Jackson Mapper? private static String getJsonSchema(Class clazz) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.WRITE_ENUMS_U ...

Issue with $.ajax({}) causing Express Session to fail saving

I'm facing an issue where I am trying to store data in an Express session, but it seems that Express is treating each AJAX request as a new session and not saving my data consistently. Here's the client-side code: $.ajax({ url: '/orders& ...

What methods can be used to report errors with Sentry while offline?

One key feature of my app is its ability to function both offline and online. However, I'm wondering how I can ensure that errors are still sent to my Sentry dashboard even when a user is offline. ...

What are the steps to create a Node.js application and publish it on a local LAN without using Nodemon?

When working on a Node.js application, I often use the following commands to build and serve it locally: //package.json "build": "react-scripts build", To serve it on my local LAN, I typically use: serve -s build However, I have been wondering how I ...

Trouble mapping an array of objects in ReactJS

I'm encountering an issue where I am unable to map through an array of objects in my component. Although I have used this map method before, it doesn't seem to be working now. Can anyone help me figure out what's going wrong? import React, ...

Error: Property 'barcodeScanner' is not readable

Currently, I am utilizing barcodescanner.js for scanning QR codes. I have successfully downloaded and linked the CaptureActivity android library to my project. However, when attempting to execute the following code: window.plugins.barcodeScanner.scan(sca ...