Extract information stored in a JSON object and input it into an array

I'm struggling to extract data from a multidimensional array.

In my .php file, I retrieve data from a database and encode it to JSON.

JSON= {"1":{"SME":"0","SAUDE":"0"}....

Desired data structure:

     array{
        0 => Array{"SME" => 1,
                   "SAUDE" =>4}
        1 => Array{"SME" => 10,
                   "SAUDE" => 0}
      }

In my .HTML:

$.getJSON('getOrgaoAno.php', function(data) {    
$.each(data, function(key, val) {
      alert(key); // Displaying the index of the first array
      alert(val); // Displaying [OBJECT] in the alert box
    }
});

How can I access the data from the second array and store it in an array in my .HTML for use in Chart.js?

UPDATE 1

Here's the data I'm receiving from the .php encoded to JSON (using console.log now, which is much easier):

The "1,2,3....9" represents the keys of the first array containing objects:

1    
Object { SECRETARIA MUNICIPAL DE DESENVOLVIMENTO URBANO : "0", SECRETARIA MUNICIPAL DE SAUDE: "0", SETOR DE RH: "0", SECRETARIA MUNICIPAL DE CULTURA, TURISMO, ESPORTE E LAZER : "0", SETOR DE CADASTRO DE IMOVEIS: "0", SECRETARIA MUNICIPAL DE DESENVOLVIMENTO ECONÔMICO, TRABALHO E MEIO AMBIENTE: "0", SETOR AGILIZA: "0" }testedados.html:21:5
2
Object { SECRETARIA MUNICIPAL DESENVOLVIMENTO URBANO : "1", SECRETARIA MUNICIPAL DE SAUDE: "0", SETOR DE RH: "0", SECRETARIA MUNICIPAL DE CULTURA, TURISMO, ESPORTE E LAZER : "0", SETOR DE CADASTRO DE IMOVEIS: "0", SECRETARIA MUNICIPAL DE DESENVOLVIMENTO ECONÔMICO, TRABALHO E MEIO AMBIENTE: "0", SETOR AGILIZA: "0" }testedados.html:21:5
3
Object { SECRETARIA MUNICIPAL DE DESENVOLVIMENTO URBANO : "0", SECRETARIA MUNICIPAL DE SAUDE: "1", SETOR DE RH: "1", SECRETARIA MUNICIPAL DE CULTURA, TURISMO, ESPORTE E LAZER : "0", SETOR DE CADASTRO DE IMOVEIS: "0", SECRETARIA MUNICIPAL DE DESENVOLVIMENTO ECONÔMICO, TRABALHO E MEIO AMBIENTE: "0", SETOR AGILIZA: "0" }testedados.html:21:5
4
Object { SECRETARIA MUNICIPAL DE DESENVOLVIMENTO URBANO : "0", SECRETARIA MUNICIPAL...

I want to extract the "keys" and "values" from the object and store them in an array.

For example:

var Desc = "Key"

var Valor = "Value"

Or should I consider changing the way I retrieve data from .php?

UPDATE 2

To select values in an array, you can use:

Two "Jquery.each" loops:

    var index = 0;
var index2 = 0;
jQuery.each( data, function( key, value ) {
      index++;
      index2 = 0;
      jQuery.each( value, function( key, value ) {
        if (index2 == 0)
         {
          arrDesc[index] = key;
          arrDesc[index] += ",";
          arrQtd[index] = value;
          index2 ++;
         }
         else
         {
          arrDesc[index] += key;
          arrDesc[index] += ",";
          arrQtd[index] += value;
         }

      });
    });

Answer №1

For effective debugging of your code, consider using console.log() over alerts. By doing so, you can easily review the output in the browser's console window (F12 to open). To add the inner object to an array, simply utilize Array.prototype.push().

var j = {"1":{"SME":"0","SAUDE":"0"}};
var arr = [];

$.each(j, function(key, val) {
    console.log(key); // 1
    console.log(val); // Object {SME: "0", SAUDE: "0"}
    console.log(val.SAUDE); // 0
    console.log(val.SME); // 0

    // adding the object to the array:
    arr.push(val);     

});

Answer №2

Make sure your PHP script named "getOrgaoAno.php" appears exactly like this:

<?php
 $data = array(/*YOUR DATA GOES HERE*/);
 echo json_encode($data);
?>

Ensure there are no additional spaces or characters before "<?php" or after "?>", as this may cause a JSON format error in JavaScript

Your JavaScript code is correct, simply log the output to the browser console.

<script type="text/javascript">
 $.getJSON('getOrgaoAno.php', function(data) {
  $.each(data, function(key, val) {
   console.log(key); //Display the index of the first array
   console.log(val); //Show [OBJECT] in the console
  })
 });
</script>

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

Attempting the transformation of jQuery ajax requests to Angular's http service

I am looking to transition my existing mobile application from using jquery ajax to angularjs for handling user authentication with server-side validation. Here is the original jquery ajax code: function validateStaffUser(username, password) { var re ...

Unable to isolate segments of a string

Looking for a way to extract two different IDs from the following string: SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9: using Javascript. The regular expression being used is : ^SPList\:(?:[0-9A-Za-z\-]+ ...

Styling Input elements with a unified border in Bootstrap

[Issue Resolved] I have been working on setting a single border between multiple inputs inside a form-group in Bootstrap. Currently, the border is only visible when the input is not focused and it is the last one. However, my expectation is for the bo ...

Struggling to retrieve the fake JavaScript data for my Vue.js table

I am a beginner in the development field and encountering the following error report while working with Vue.js 3 115:5 error 'vendorTable' is assigned a value but never used no-unused-vars 115:23 error 'Vue' is not defined no- ...

Extract data from a JSON-encoded array using JavaScript

I sent a JSON encoded array to JavaScript. Now I want to access that array to retrieve the different elements. When I print it out using console.log(), I see this array: array(1) { [16]=> array(2) { [3488]=> array(1) { [0]=> ...

Tackling the challenge of merging PDF files and designing a Table of Contents feature reminiscent of Acrobat in Node.js and JavaScript

I am currently implementing the following code snippet: const pdfmerger = require('pdfmerger') var pdfStream = pdfmerger(array_of_pdf_paths) var writeStream = fs.createWriteStream(final_pdf_path) pdfStream.pipe(writeStream) pdfmerger(array_of_pd ...

Unleashing the power of TypeScript with Solid JS Abstract Class

Why am I getting an undefined error for my calcUtilisation method when using an Abstract Class as the type in createStore? Is there a way to utilize a type for the data along with a method within the same class for createStore? abstract class Account { ...

Update all values in JSON data without the need to iterate through each one

Below is a sample that demonstrates how to use the JSON_MODIFY function or another method to update all "disc" values to "100" without manually updating each array item in a loop: create table #temp_data (json_text nvarchar(max)) insert into #temp_data s ...

Creating a Button with Icon and Text in TypeScript: A step-by-step guide

I attempted to create a button with both text and an icon. Initially, I tried doing it in HTML. <button> <img src="img/favicon.png" alt="Image" width="30px" height="30px" > Button Text ...

What is the process of retrieving the JSON array containing data from Reddit?

I am struggling to grasp the idea of JSON arrays and how to pinpoint a specific array from a JSON response. My objective is to retrieve the "URL" key value from the "data" objects within the "children" array at http://www.reddit.com/r/gifs/.json, but I am ...

The div height adjustment peculiarities in IE7 and IE8 are causing quite a stir

I recently encountered a problem with my HTML/JS code that I thought was simple. The code is designed to expand the size of a div on mouseover and then collapse it back on mouseout. Here's how the code looks: CSS: .sign-in-up { position: absolut ...

Is it possible to change the button class within a div while ensuring only the last one retains the change?

Here is a code snippet I'm using to switch between classes for buttons: $('button').on('click', function(){ var btn=$(this); if(btn.attr('class')=='tct-button'){ btn.removeClass('tct-button ...

Strange issue: the code appears to be running multiple times with just one click

I've implemented a commenting system with a like feature. However, I'm facing an issue where sometimes clicking the like link results in sending multiple requests (up to 8-9) per click. This problem also occurs with another jQuery code that is tr ...

Creating functionality with a native JavaScript plugin within a directive and test suite

I have a custom JavaScript plugin that is integrated within a directive and utilized in an Angular manner. Snippet of the directive, export default function () { 'use strict'; return { restrict: 'E', scope: { map: &apo ...

Switch back and forth between two different function loops by clicking

I have implemented two sets of functions that animate an SVG: one set runs in a vertical loop (Rightscale.verticalUp and Rightscale.verticalDown) and the other in a horizontal loop (Rightscale.horizontalUp or Rightscale.horizontalDown). On clicking the SVG ...

Fetching a value by key from a JSON object in a Node.js script

How can I extract the id value from this JSON object? answerTag: [ '[{"id":64,"name":"Coronary Artery Disease"}]', '[{"id":64,"name":"Coronary Artery Disease"}]' ], risk: '1' } ...

Create a pandas dataframe by processing JSON data retrieved from a web API

I'm currently working on converting nested JSON objects obtained from 'https://api.data.gov.sg/v1/transport/carpark-availability' into a dataframe. However, the data retrieved in the dataframe is incomplete. Here is the code I have been usi ...

React SVG not displaying on page

I am facing an issue with displaying an SVG in my React application. Below is the code snippet: <svg className="svg-arrow"> <use xlinkHref="#svg-arrow" /> </svg> //styling .user-quickview .svg-arrow { fill: #fff; position: ...

The Context API leaves me feeling lost and confused

I am currently utilizing Auth0 for user sign up. My goal is to extract the user id listed under sub:value, and then add it to my database to associate it with a user's post. To achieve this, I am attempting to utilize a Context API to retrieve the use ...

a tutorial on linking component data to a prop value

Is there a way to connect the searchString value in my Vue component to the item value in the html template it uses? I need to pass this value to the method called in my Ajax request. Vue: Vue.component('user-container-component', { props: ...