Tips for transforming a JSON array into a JavaScript 2D array

I am struggling to figure out how to convert the given JSON data into a JS 2D array directly from HTML.

[{"fields": {"diameter": 23.0, "neighbourhood": "WEST END"}, "model": "hug.tree", "pk": 345}, 
 {"fields": {"diameter": 14.0, "neighbourhood": "MOUNT PLEASANT"}, "model": "hug.tree", "pk": 484}]

The desired output should resemble something like this:

[[23.0, 'WEST END'], [14.0, 'MOUNT PLEASANT']]

Your assistance in this matter would be greatly appreciated!

Answer №1

This code snippet is designed to function with all fields within the "fields" category, not limited to just diameter or neighborhood.

See it in action:

var items = [{"fields": {"diameter": 23.0, "neighbourhood": "WEST END"}, "model": "hug.tree", "pk": 345}, {"fields": {"diameter": 14.0, "neighbourhood": "MOUNT PLEASANT"}, "model": "hug.tree", "pk": 484}];

var i = 0, result = [];

while(i < items.length){
    result.push([])
    for(var key in items[i].fields){
        result[result.length-1].push(items[i].fields[key])
    }
    i++
}

document.write(JSON.stringify(result, null, 4));

Answer №2

Iterate through each entry in the json array and create a new sub-array in the result array containing the diameter and neighborhood values.

var json = [{"fields": {"diameter": 23.0, "neighbourhood": "WEST END"}, "model": "hug.tree", "pk": 345}, {"fields": {"diameter": 14.0, "neighbourhood": "MOUNT PLEASANT"}, "model": "hug.tree", "pk": 484}];
var done = [];
json.forEach(function(object){
    done.push([object.fields.diameter, object.fields.neighbourhood]);
});

console.log(done);

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 save JavaScript array information in a database?

Currently working on developing an ecommerce website. My goal is to have two select tags, where the options in the second tag are dynamically populated based on the selection made in the first tag. For example, if "Electronics" is chosen in the first tag f ...

How to manage access controls for the Admin Page in node.js

Hi everyone, I am facing an issue with my admin page access control on my application. I want to restrict access to all users except the one named John. In my app.js file, here is what I have: app.get('/admin', requireLogin, function(req, res){ ...

Executing asynchronous function in Angular using Typescript

My team and I are new to Angular and we are facing a challenge with invoking methods in sequence and returning a value. The issue is that the return statement is being executed before the completion of the execution process. We have tried various approac ...

Is there a way to asynchronously load image src URLs in Vue.js?

Why is the image URL printing in console but not rendering to src attribute? Is there a way to achieve this using async and await in Vue.js? <div v-for="(data, key) in imgURL" :key="key"> <img :src= "fetchImage(data)" /> </div> The i ...

Generating Dynamic Object Keys following Array Mapping

I have a vision of creating a sophisticated data structure resembling the configuration below: slots: { 'slot_1': { id: 'slot_1', associatedCard: {} }, 'slot_2': { id: 'slot_2& ...

Transfer the "file" from the busboy to the GM for FTP uploading

I'm looking to resize an uploaded image using nodejs and send it via ftp. I'll be utilizing nodejs, busboy, GraphicsMagick, and jsftp. var uploadFile = function(dir, req, cb) { req.busboy.on('file', function(fieldname, file, filename, ...

Comparing the use of input parameters to pass information in node.js versus the use

I'm grappling with the concept of when to inject a response into a function or call a function and retrieve something from it. Specifically in Node.js. Do functions in Node.js actually return data, or is it primarily about passing arguments and utili ...

Highlighting text in React using hover effects on list elements

Imagine having HTML / JSX structured like this: <ul> <li>First point in list</li> <li>Second point in list</li> </ul> and the goal is to highlight a contiguous range that spans multiple list items: <ul> < ...

How can I retrieve JSON data from a URL on a Windows Phone, incorporating user input?

After following the steps outlined in this tutorial, I was able to create Restful Web Services that display JSON output from my MySQL database. Although I successfully completed the task, I now face a new challenge; my database contains nearly 100 tables ...

Issue with Pagination functionality when using Material-UI component is causing unexpected behavior

My database retrieves data based on the page number and rows per page criteria: const { data: { customerData: recent = null } = {} } = useQuery< .... //removed to de-clutter >(CD_QUERY, { variables: { input: { page: page, perPag ...

Error Unhandled in Node.js Application

I have encountered an issue in my NodeJS application where I have unhandled code in the data layer connecting to the database. I deliberately generate an error in the code but do not catch it. Here is an example: AdminRoleData.prototype.getRoleByRoleId = ...

Strategies for sorting through Ansible JSON data efficiently

Utilizing Ansible Automation for Linux Patching. After completing the patching process, I need to extract specific details from the JSON output. Below is the code snippet that does not provide accurate output from the JSON file when executing the playbook ...

Enhancing Vue.js functionality with extra information stored in local storage

I've created a To Do List app where you can add tasks using a button. Each new task is added to the list with a checkbox and delete button in front of it. I'm trying to save all the values from the inputs and the checked checkboxes on the page on ...

Using jQuery to slide in dynamically generated content

I am in the process of developing a straightforward content slider that has the capability to manage dynamically added content. Unfortunately, none of the supposedly "lightweight" plugins I came across offered this functionality or, if they did, it was not ...

Unable to convert JSON data from kafka to pandas format

Hello, I have the following code to consume Kafka data: bootstrap_servers = ['localhost:9092'] topicName = 'testapp5' consumer = KafkaConsumer (topicName, group_id ='group1',bootstrap_servers = bootstrap_servers) for msg i ...

Exploring deep object structures in C#

My current challenge involves extracting specific details from an object using the Google Books API. To achieve this, I have deserialized the content into two POCOs in order to access a nested object. My main hurdle lies in retrieving properties such as ti ...

Chunk loading in IE 11 has encountered an error

Having an issue with my website which is created using Angular 5. It seems to be malfunctioning in IE 11, and I am encountering the following error in the console: https://i.stack.imgur.com/Ek895.png Any insights on why my Angular code isn't functio ...

Registering components globally in Vue using the <script> tag allows for seamless integration

I'm currently diving into Vue and am interested in incorporating vue-tabs into my project. The guidelines for globally "installing" it are as follows: //in your app.js or a similar file // import Vue from 'vue'; // Already available imp ...

Refreshing jQuery via Ajax Response

In our JSF2 application, we encounter situations where we need to re-invoke the JavaScript (specifically jQuery for UI styling) when making Ajax calls. However, it seems that the JavaScript functions are not being called upon receiving the Ajax response fr ...

Utilizing an Empty Array within an AngularJS Controller Function Invoked by a Directive

I have encountered a tricky issue that appears to be simple, but I am struggling to find a solution. Currently, I am developing a to-do list application using Angular and Angular-Material. The main part of the application is located in a file named main. ...