The initial line is the only place where JSON headers are displayed

Currently diving into the world of JavaScript and tackling a project head-on. However, I've hit a roadblock as the JSON file I'm working with looks different from what I'm used to. Can anyone assist me in figuring out how to display this data in my HTML file?

{
  "values": [
    [
      “name”,
      “age”,
      “location”
    ],
    [
      “Alice”,
      “28”,
      “Florida.”
    ]
]
}

I'm accustomed to working with this format

[name:"Alice",age:"28",location:"Florida"]
[name:"Bob",age:"27",location:"Texas"]

Is there a way to transform it to match that style?

Appreciate any help!

Answer №1

Alright, so without those strange quotes, it's pretty straightforward

const dataValues = {values: [["name","age","location"],["Alice","28","Florida."]]};

const [labels, ...info] = dataValues.values

const finalResult = info.map(info => Object.fromEntries(labels.map((label, index) => [label, info[index]])));

console.log(finalResult);

Or

Doing it like a pro...

const dataValues = {values: [["name","age","location"],["Alice","28","Florida."]]};

const {values: [labels, ...details]} = dataValues;

const finalResult = details.map(info => Object.fromEntries(labels.map((label, index) => [label, info[index]])));

console.log(finalResult);

Answer №2

You are provided with a 2-dimensional array, in which the first array consists of keys and the second array contains values.

Utilize the function below to convert this into the desired output.

const arr = [["name","age","location"],["Alice","28","Florida."]];

function arrToObject (arr){
    //assuming header
    var keys = arr[0];
    //extract keys from the main array
    var newArr = arr.slice(1, arr.length);

    var formatted = [],
    data = newArr,
    cols = keys,
    l = cols.length;
    for (var i=0; i<data.length; i++) {
            var d = data[i],
                    o = {};
            for (var j=0; j<l; j++)
                    o[cols[j]] = d[j];
            formatted.push(o);
    }
    return formatted;
}

console.log(arrToObject(arr));

By the way, this function was discovered from this source

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

Trouble displaying static files in Angular/Express app on Heroku, while they are functioning as expected on local environment

After deploying to Heroku, I noticed that the css and javascript files in the 'public' directory were missing, resulting in 404 errors. Strangely, these files exist locally without any issues. In my app.js file, I have included the following: a ...

Transferring request body data between routes in Express: A guide

In my MERN application, there are two specific routes in place. The first route is designated for 'Storing Data' and is referred to as the 'data' route. The second route is used for 'Register User' functionalities and is known ...

Issue experienced with Vue2 where utilizing a computed property to filter a nested v-for structure

I have a unique HTML challenge that requires me to iterate through an unconventional data setup. The information is retrieved in two separate parts from Firebase: one for categories and another for businesses. The structure of the data is as follows: Busi ...

Please note: With React 18, the use of ReactDOM.render is no longer supported. Instead, we recommend using create

I encountered an issue while attempting to link my React application with a MongoDB database. Here is the code snippet where the problem occurred: //index.js ReactDOM.render( <React.StrictMode> <BrowserRouter> <App /> &l ...

What is the process for adding a download link to my canvas once I have updated the image?

Is it possible to create a download link for an image that rotates when clicked, and then allows the user to download the updated image? Any help would be appreciated.////////////////////////////////////////////////////////////////////// <!DOCTYPE ht ...

What could be the reason for my array parameter not being included in the POST request

When working on my laravel 5.7 / jquery 3 app, I encountered an issue while trying to save an array of data. After submitting the form, I noticed that only the _token parameter is being sent in the POST request as seen in the browser console: let todos_co ...

Changing the position of an image can vary across different devices when using HTML5 Canvas

I am facing an issue with positioning a bomb image on a background city image in my project. The canvas width and height are set based on specific variables, which is causing the bomb image position to change on larger mobile screens or when zooming in. I ...

The Meteor update is unsuccessful on the Mongo Sub Collection and will not continue

I am currently facing an issue with updating a specific object within an array in my object based on a value. Whenever I try to add the update code, the function gets stuck at that point without proceeding further. None of the console.log calls after the u ...

Tool to track character limits in multiple text fields

I'm facing a challenge with a form that includes 3 text areas, a copy button, and a reset button. My goal is to concatenate all the characters in the text areas to get a sum which will be displayed next to the copy/reset button. The character limit is ...

Customize Bootstrap 4 Carousel: Set specific data-interval for each slide

I'm facing an issue with setting the data-interval for each slide of the carousel. I came across a JavaScript code snippet on stackoverflow, but it's not functioning as expected. (Twitter Bootstrap Carousel slide duration) In my HTML, each slide ...

Managing the React Router component as a variable

I'm currently working on integrating React-Router into an existing React app. Is there a way to use react-router to dynamically display components based on certain conditions? var displayComponent; if(this.state.displayEventComponent){ {/* ...

Steps to troubleshoot the TypeError: cv.Mat is not a constructor in opencv.js issue

Encountering a problem while trying to use opencv.js for detecting aruco markers from my camera. Each time I attempt to utilize the method let image = new cv.imread('img'); An error keeps popping up: TypeError: cv.Mat is not a constructor ...

Send an array from PHP to jQuery using AJAX, then send the array back from jQuery to PHP

I am facing a dilemma where I am passing an array from PHP to jQuery AJAX using `json_encode` and storing it in an empty array declared in the jQuery script as `var myarr = []`. Later in the same script, I am sending the same array `myarr` back to the PHP ...

Issues with ng-repeat causing the Angular Editable table to malfunction

<table class="table table-bordered"> <tbody> <tr ng-repeat="playerOrTeam in template.editableTable track by $index"> <td style="text-align: center;" ng-repeat="playerOrTeamCat in playerOrTeam track by $index"> ...

Alert popup onclick feature is malfunctioning

SOLVED: I finally figured out the issue and it is now working perfectly. I had to manually switch to Chrome instead of using the Brackets live viewer. I want an alert box to pop up when the "Home" link is clicked on my website. I tried creating a separate ...

Is your webpage slow to respond after a page-refresh? (Delayed HTML rendering causing lag)

Whenever I adjust the screen size to that of a phone or any device smaller than 768px, the search bar doesn't display in its proper position until the page is refreshed. It should be correctly placed right from the start. Furthermore, when I resize th ...

Steps to create a toggle feature for the FAQ accordion

I am currently working on creating an interactive FAQ accordion with specific features in mind: 1- Only one question and answer visible at a time (I have achieved this) 2- When toggling the open question, it should close automatically (having trouble with ...

What is the process for retrieving an object from a node.js server using JSON.stringify() in a JavaScript file?

Looking to organize my code, I want to separate the JavaScript from my page and link it through a file instead of having it embedded within script tags. The issue arises when I receive a "SyntaxError: expected expression, got '<' " in Firefox ...

"Enhancing User Authentication with Firebase Email Verification in React Native

Does Firebase have a feature that allows me to verify if an email confirmation has already been sent to a user? I am able to check validation, but I need to determine whether the verification email has already been sent in order to decide if it needs to be ...

Updating all the direct components within the corresponding category with jQuery

Here is the HTML content I am working with: <li class="info"> info<li> <li class="other"> info<li> <li class="other"> info<li> <li class="Error"> error<li> <li class="other"> error<li> < ...