Transform json nested data into an array using JavaScript

Can anyone assist me in converting Json data to a Javascript array that can be accessed using array[0][0]?

[
    {
        "Login": "test1",
        "Nom": "test1",
        "Prenom": "test1p",
        "password": "124564",
        "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="097d6c7a7d38496e64686065276a6664">[email protected]</a>"
    },
    {
        "Login": "test2",
        "Nom": "test2",
        "Prenom": "test2p",
        "password": "124564",
        "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1d5c4d2d593e1c6cc120a">[email protected]</a>"
    }
]

I have tried the provided code but I am unable to access specific data (such as 'Nom') in the array. How can I achieve this?

Code.js

var data = [
    {
        "Login": "test1",
        "Nom": "test1",
        "Prenom": "test1p",
        "password": "1267846",
        "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="becadbcdca8ffed9de7bfdfd20ed3d123bbde94dec39b959599dd99">[email protected]</a>"
    },
    {
        "Login": "test2",
        "Nom": "test2",
        "Prenom": "test2p",
        "password": "124494",
        "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="13677660672153747e727a7f3d707c792528398b97291d29">[email protected]</a>"
    }
];

function data_to_array(data) {
    var array = [];
    for (var key in data) {
        var value = data[key];
        if (typeof value === 'string') {
            array[key] = value;
        } else {
            array[key] = data_to_array(value);
        }
    }
    return array;
}

var array = data_to_array(data);
for(var i in array)
    console.log(array[i]);   

After parsing, trying to access it with myArr[0][1] results in 'undefined'.

Answer №1

var newArray = [];

for (var index=0, length=data.length, temp; index<length; index++) {
  temp = [];
  for (var key in data[index]) {
    if (data[index].hasOwnProperty(key)) {
      temp.push(data[index][key]);
    }
  }
  newArray.push(temp);
}

newArray;
// [
//   ["test1","test1","test1p","124564","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e5a4b5d5a1f6e49434f4742004d4143">[email protected]</a>"],
//   ["test2","test2","test2p","124564","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b1f0e181f592b0c060a020745080406">[email protected]</a>"]
// ]

If es5 functions are available, you can utilize Array.prototype.map and Object.keys

var newArray = data.map(function(elem) {
  return Object.keys(elem).map(function(k) { return elem[k]; });
});

newArray;
// [
//   ["test1","test1","test1p","124564","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="62160711165322050f030b0e4c010d0f">[email protected]</a>"],
//   ["test2","test2","test2p","124564","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="26524355521466414b474f4a0845494b">[email protected]</a>"]
// ]

Answer №2

There seems to be a confusion between arrays and objects. Remember that all arrays are objects, but not all objects are arrays. It appears that the "for..in" loop is being used incorrectly when dealing with an array containing objects. Adding more console statements and conducting checks can help you understand how it functions. Here is the required solution for your situation:

var data = [
    {
        "Login": "test1",
        "Nom": "test1",
        "Prenom": "test1p",
        "password": "1267846",
        "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd89988e89ccbd9a909c9491d39e9290">[email protected]</a>"
    },
    {
        "Login": "test2",
        "Nom": "test2",
        "Prenom": "test2p",
        "password": "124494",
        "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94e0f1e7e0a6d4f3f9f5fdf8baf7fbf9">[email protected]</a>"
    }
];

function data_to_array(data) {
    var array = [];
    for (var i=0;i<data.length;i++) {
        var obj = data[i];
        array[i] = new Array();
        for(var key in obj) {
            array[i].push(obj[key]);
        }
    }
    return array;
}

var array = data_to_array(data);
console.log(array);

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

What is the best way to retrieve data from a multi-dimensional JSON array within SQL Server?

I am currently struggling with extracting data from a multidimensional JSON array in SQL Server using 'OPENJSON' to convert JSON data to SQL. The issue lies in fetching the data from the multidimensional array. Declare @Json nvarchar(max) Set @ ...

Creating an associative array with two SQL queries: A step-by-step guide

I am looking to create an associative array that will interact with two MySQL tables named cs_lots and cs_lots_history. Below is the PHP code snippet I have written: $rows = array(); $res2 = mysql_query("SELECT * FROM cs_lots WHERE active_lot='1&apo ...

Ways to extract the ID by iterating through buttons

I encountered a message in my browser while looping through buttons with onclick function(). Are there any alternative solutions? Error handling response: TypeError: self.processResponse is not a function at chrome-extension://cmkdbmfndkfgebldhnkbfhlneefd ...

Aurelia's navigation feature adds "?id=5" to the URL instead of "/5"

I have set up my Aurelia Router in app.ts using the configureRouter function like this: configureRouter(config, router: Router) { config.map([ { route: ['users', 'users/:userId?'], na ...

HTML/JavaScript: Embrace the Power of Dynamic Page

I have a unique element in my HTML code: <image src="http://..." style='...'> Using Python-Flask, I pass on a dynamic source address and save it as window.dynamicEmbedding. Now, during page load, I want to change the image's ...

Triggering a jQuery ajax request upon pressing a key on the keyboard

When a user inputs text into an <input> element, I'm using ajax to send a request to the server. Here's how it looks: $('#my-input').bind("input", function(event){ // ajax request code }); My concern is that too many requests ...

PHP: Sending multiple values under a single name

Here's the code I'm currently working with. It includes a form with 6 inputs. The last 3 inputs are named firstanswer, secondanswer, and thirdanswer. <form action="addsurvey.php" method="post"> <input type="text" name="surveyname"> ...

Stagnant className in map persisting despite changes being made

I am in the process of updating my react className based on changes to the active status within the sites variable, which is iterated over with a map function. The issue I'm facing is that the 'inactive' className persists even when the act ...

Detecting collisions on a pixel-by-pixel basis within Javascript/Jquery/Gamequery

Currently, I am working on developing a web game using Jquery with the GameQuery plugin. However, I have encountered an issue where the GameQuery plugin does not support per pixel collision detection, only bounding boxes collision detection. Is there a way ...

Send a webhook post request without causing a redirection

Is there a way to send a post request to a webhook without redirecting the user directly to the webhook URL, after validating their input? ...

Discover the method for obtaining a selected element in a bootstrap dropdown that is dynamically populated

Similar to the question asked on Stack Overflow about how to display the selected item in a Bootstrap button dropdown title, the difference here is that the dropdown list is populated through an ajax response. The issue arises when trying to handle click ...

Tips for modifying the response of an ExpressJS server following a timeout on a POST request

Currently, I'm in the process of creating a server using Node.js and ExpressJS. The issue arises when the client sends a POST request instructing the server to control an external device's movement either up or down. My goal is for the server t ...

Issue with height in self-invoking function not functioning correctly

Issue with height not functioning correctly inside self-invoking function, but works fine within (document).ready(function() (function($){ var clientHeight = document.getElementById('home').clientHeight; alert(clientHeight); })(jQuery); <di ...

The setState function in React is not being updated within the callback function

I've encountered an issue while working on a project in React. The puzzling part is why the variable selectedRow remains null even after using the setSelectedRow function inside the onClick callback. Despite my efforts to log it, the value always retu ...

In order to ensure JavaScript can be universally applied to all images, it needs to be made more generic

I have developed JavaScript functions to enable zoom in and zoom out functionality for an image through pinching gestures. Now, I aim to refactor the code below so that I can include it in a shared JavaScript file. var scale = 1; var newScale; ...

Steps to resolve the TypeError: RelatedManager object does not support iteration

I am working with two models, Meeting and Meetingmemeber, to store information about a meeting and the invited participants. Here is how I have set up the serializer: class MeetingSerializer(serializers.ModelSerializer): location = MeetingLocationSer ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

The content momentarily flashes on the page during loading even though it is not visible, and unfortunately, the ng-cloak directive does not seem to function properly in Firefox

<div ng-show="IsExists" ng-cloak> <span>The value is present</span> </div> After that, I included the following lines in my app.css file However, the initial flickering of the ng-show block persists [ng\:cloak], [ng-cloak], ...

Tips on obtaining checkbox values other than "true"

Having trouble retrieving the values of selected checkboxes instead of displaying "Custom Category"? I've attempted to access the values and attributes with no success. I'm aiming to display the values of the selected checkbox. app.component.ht ...

The issue of why padding left is not functioning correctly in Bootstrap version 5.3.1

</head> <body> <header class="bg-info "> <div class="container"> <div class="row text-white"> <div class="col-md-6 p-3 pl-6 "> ...