retrieve information stored as a JSON object

Below is the json object that I am working with:

$dati = array(
    "data" => array(
        'address_complete'=>$data->results[0]->formatted_address, 
        'address_square'=>$data->results[0]->address_components[1]->long_name,
        'location'=>$data->results[0]->address_components[2]->long_name,
        'postal_code'=>$data->results[0]->address_components[7]->long_name,
        'data_ora'=>$tmp_date
    ),
    "str" => array("n".$i=>$array_db[username]),
    "index" => $i
);

I am trying to display the data from str. Here is what I have written:

... success:function(msg){
        if(msg){
                var j = "n"+2;
                $("#location").html(msg.str.j);
        }else{
            $("#location").html('Not Available');
        }
    },

However, the output appears empty. It works correctly when I directly reference n2 instead of using variable j in $("#location").html(msg.str.j);. Why does this happen?

Answer №1

The reason for this issue is attempting to append a string to an object.

An example of what you may be doing incorrectly is trying something like msg.str.'n2', which is not the same as msg.str.n2.

Let me provide you with a functional example right away:

var person = {
    firstName: 'John',
    lastName: 'Doe'
};
alert(person.firstName);

The output of this code will be "John"

Now, consider the following example:

var person = {
    firstName: 'John',
    lastName: 'Doe'
};
var key = 'firstName';
alert(person[key]);

The result of this alert will be "undefined".

Update: For arrays within an object:

var person = {
    firstName: 'john',
    lastName: 'doe',
    array: ['first','second','third']
};
for(var i = 0; i<person.array.length; i++) {
    alert(person.array[i]);
}

If you wish to access it using a key, then use :

var key = 'n2'; 
alert(msg.str[key]); 

The correct solution would be:

... success:function(msg){
        if(msg){
                var k = "n"+2;
                $("#output").html(msg.str[k]);
        } else {
            $("#output").html('Not Available');
        }
    },

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 an array of random integers in Rails based on a given number

I am looking to create 5 buttons with unique values based on a single integer. For instance, if the integer is 30, I want buttons with values of 10, 20, 30, 40, and 50. value = 30 int1 = value - 20 int2 = value - 10 int3 = value int4 = value + 10 int5 = v ...

What is the best way to transfer variables to a different page through a pop-up window?

I'm working with a function that converts the Id of the clicked element into a variable, then opens a new window with a different page. How can I access or utilize this variable on the newly opened page? var idToWrite = []; $(function(){ $(".szl ...

The directive attribute in AngularJS fails to connect to the directive scope

I have been attempting to pass an argument to a directive through element attributes as shown in the snippet below: directive app.directive('bgFluct', function(){ var _ = {}; _.scope = { data: "@ngData" } _.link = function(scope, el ...

Encountering 'Unacceptable' error message when attempting to retrieve response via AJAX in the SPRING

I'm encountering an issue with my code where I am trying to retrieve a JSON array response from a controller class. Whenever I send a request from JavaScript, I receive a "Not Acceptable" error. Can someone please assist me in identifying the bug in m ...

Establish a Connection Between Local Mongo Database and Your Application

I have successfully set up a local MongoDB connection with a React, GraphQL application. All configurations are in place and functioning properly as far as I can tell. To visually view my MongoDB databases, I have installed Compass. The content of the Ser ...

Having trouble generating a JSON file from user input upon clicking the button in a C# Windows Form application

Currently, I am in the process of developing a C# application using VS2017 windows form application. The primary functionality of this app is to take user input and save it into a JSON file. However, there's a limitation where only one user input can ...

Utilizing PHP variables to dynamically assign names to radio input tags, and then extracting their values using jQuery or JavaScript

I am facing an issue with my PHP file that generates radio buttons based on unique pets ids. The variable $idperro is constantly changing to distinguish the set of radio buttons. My goal is to insert the value inside the p tag. Here's the PHP code sn ...

Choose a random cell in Jquery every second

I am searching for a method to choose one div out of sixteen and change its CSS backgrounds. This selection needs to occur every second, so a new div is selected from the group each second. I am struggling with implementing the "every second" functionalit ...

Triggering blur event manually in Ionic 3

Is there a way to manually trigger the blur event on an ion-input element? The ideal scenario would be with an ionic-native method, but any javascript-based workaround will suffice. My current configuration: Ionic: ionic (Ionic CLI) : 4.0.1 (/User ...

Utilizing Vuex Store in Blade Template | Laravel and Vue.js

I'm trying to figure out how to access a method or variable that is defined in the Vuex 4 store within my Blade file. Currently, I am utilizing a compiled app.js from Vite. While I can easily access the store in Vue.js components, I am curious if it&a ...

What is the best way to transfer data from a controller to a router in a node.js application

I have a folder structure with two files: a controller and a router. I have successfully pulled data from MongoDB in the controller, but I am having trouble passing it to the router in order to send it to the client using an API. Any ideas on what might be ...

The server encountered an unexpected error while processing the request, possibly due to a

My JavaScript file includes an interval function that calls the following code: setInterval(function() { $.getJSON('/home/trackUnreadMsgs', function(result) { $.each(result, function(i, field) { var temp = "#messby" + result[i].from; ...

Three.js is experiencing difficulties in loading textures for custom Geometry with ShaderMaterial

A Geometry (pyramid) is defined here with four vertices and 4 faces - var geom = new THREE.Geometry(); geom.vertices.push(new THREE.Vector3(0,100,0), new THREE.Vector3(-100,-100,100), new THREE.Vector3(0,-100,-100), new THREE.Vector3(100,-100,100)); geom ...

Neglecting asynchronous Ajax functions once they have been called

I currently have a function that looks like this: $("#transfer").click(function(){ var token_rec = $("#token_rec").val(); var user_rec = $("#user_rec").val(); var subdomain_rec = $("#subdominio_rec").val(); var req_rec ...

JXBrowser comparable

In a Java project of mine, I have been utilizing JXBrowser to showcase Google Maps for route tracing purposes. However, the license for JXBrowser has recently expired after just one month. Unfortunately, simply requesting another license is not an option ...

Ways to conceal numerous objects

I need to create a function where I can hide multiple elements by pressing a button based on the value of checkboxes. If a checkbox is checked, the corresponding element should be hidden. Currently, I have some code that only works for the first element: ...

Obtain Outcome from a Nested Function in Node.js

I'm grappling with the concept of manipulating the stack in JS and hoping this exercise will provide some clarity. Currently, I'm attempting to create a function that makes a SOAP XML call, parses the data, and returns it when called. While I c ...

Is there a way to update the parent component when changes occur in the child component?

I have been working on a book tracking application that allows users to keep track of the books they have read or plan to read. The app is built using Vue.js on the front end and Express.js on the server side. It consists of three lists or categories for o ...

Obtain the orientation of the threejs scene and camera to establish the initial perspective

Currently, I am facing challenges in configuring the default camera position and orientation for my THREE.JS demo. I aim to manually adjust the view/scene/camera through trackball interaction and then find a way to set the correct camera settings to establ ...

What is the most effective way to transfer values from an array to a constructor in C++?

I have developed a program that reads data from a file and generates objects based on that data. The values of these objects can vary, so I have implemented an expandable array to accommodate them. However, I am facing some challenges when trying to pass t ...