Convert an object to a custom array using JavaScript

I need to transform the following object:

"age": [
  {
     "Under 20": "14",
     "Above 40": "1"
  }
]

into this structure:

 $scope data =  {rows:[ 
    {c: [
        {v: "Under 20"},
        {v: 14}
    ]},
    {c: [
        {v: "Above 40"},
        {v: 1},
    ]}
 }]

I attempted:

 $.map(resp.age, (el, key) => {
        arr.push({c: [{v: el}, {v: el}]});
 });

Although I am familiar with using $.map and arr.push, I'm struggling to extract the key Under 20 along with its corresponding value 14.

Is there a better way to achieve this task?

Answer №1

Here is a solution for your problem:

function transformData(data) {
    var agesData = data["age"][0];
    return {
        'rows': Object.keys(agesData).map(function(key) {
            return {'c': [{'v': key}, {'v':parseInt(agesData[key])}] };
        })
    }
}

// Example usage:
transformData({
    "age": [{
        "Under 20": "14",
        "Above 40": "1"
    }]
});

The code snippet above will generate the following output:

{"rows":[{"c":[{"v":"Under 20"},{"v":14}]},{"c":[{"v":"Above 40"},{"v":1}]}]}

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

fluctuating random percentage in JavaScript/jQuery

I am currently faced with the challenge of selecting a random number based on a given percentage ranging from 0 to 5. 0 - 25% (25/100) 1 - 25% (25/100) 2 - 20% (20/100) 3 - 15% (15/100) 4 - 10% (10/100) 5 - 5% (5/100) However, there are instances where ...

Is it possible to pass a class method to an onClick event from within the render method in ReactJS?

Excuse my lack of experience, but I haven't been able to find a solution to this yet. I am attempting to utilize a class method as a callback for the onClick event in my JSX. Below is the code for my App component: import React from 'react&apo ...

Loading a series of images in advance using jQuery

I have a series of frames in an animation, with file names like: frame-1.jpg, frame-2.jpg, and I have a total of 400 images. My goal is to preload all 400 images before the animation begins. Usually, when preloading images, I use the following method: v ...

Alert: VirtualizedList warns of slow updates for a large list despite optimized components

Struggling with avoiding the warning message "VirtualizedList: You have a large list that is slow to update" while utilizing the <FlatList> component in React-Native. Despite thorough research and attempts at finding a solution, including referencin ...

Node.js not resetting array properly

I have successfully set up a Node+Express API that is working smoothly, but I am facing an issue with returning responses for complex queries. The problem lies in the fact that the variable where I store the response data is not being reset between differe ...

What is the best way to prevent a folder from being included in the next js build process while still allowing

I am faced with a challenge involving a collection of JSON files in a folder. I need to prevent this folder from being included in the build process as it would inflate the size of the build. However, I still require access to the data stored in these file ...

Encountering a WriteableDraft error in Redux when using Type Definitions in TypeScript

I'm facing a type Error that's confusing me This is the state type: export type Foo = { animals: { dogs?: Dogs[], cats?: Cats[], fishs?: Fishs[] }, animalQueue: (Dogs | Cats | Fishs)[] } Now, in a reducer I&a ...

Exploring asynchronous data handling in AngularJS using promises

Currently, I am working on a single page application using angularJS and encountering some difficulties in storing asynchronous data. In simple terms, I have a service that contains my data models which are returned as promises (as they can be updated asy ...

AngularJS url update event

In order to gather statistical data, I am interested in tracking how many times the URL has been changed. To achieve this, I have set up a counter that will increment each time the URL is modified. Does anyone have a solution for this? ...

Major Technical Issues Plague School-wide Celebration

In my JavaScript code, I am creating a 16x16 grid of divs. Each div should change its background color from black to white when the mouse enters (inherited based on a common class). However, I am facing an issue where all the divs change color simultaneou ...

Fixing the mobile display issue with react-responsive-carousel

I am relatively new to ReactJS and I am looking to develop a responsive Carousel. Here is the code snippet that I have currently: To achieve a responsive Carousel for both desktop and mobile devices, I utilized the react-responsive-carousel library. The ...

What is the best way to change a JavaScript variable into a PHP variable?

I am interested in converting my JavaScript variable to a PHP variable... Currently, I have the following scenario - in the code below there is a variable e, but I would like to utilize e in PHP as $e: <script> function test() { var e = documen ...

Unidentified googletagmanager detected in vendors segment

Recently, my ad blocker detected an unfamiliar Google Tag Manager request originating from a chunk provided by one of my vendors. Is it typical for tracking to be embedded in dependencies like this? And what type of information can be collected from my we ...

Animating Array of Paragraphs with JQuery: Step-by-Step Guide to Displaying Paragraph Tags Sequentially on Each Click

var phrases = ['phraseone', 'yet another phrase', 'once more with feeling']; $(".btn").on('click', function() { for(var i=0; i < phrases.length; i++) { container.innerHTML += '<p>' + ...

Prevent scrolling within input field

I have a text entry field with background images that separate each letter into its own box. Unfortunately, an issue arises when I reach the end of the input: the view automatically scrolls down because the cursor is positioned after the last letter enter ...

Angular: display many components with a click event

I'm trying to avoid rendering a new component or navigating to a different route, that's not what I want to do. Using a single variable with *ngIf to control component rendering isn't feasible because I can't predict how many variables ...

Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag. For example, you can use the following code snippet: [...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue ...

Performing a simulated click on a dynamically inserted element using pure JavaScript

I am faced with the challenge of programmatically navigating a ReactJS-based website in a looped workflow. The process involves clicking on Element1, dynamically altering the web page to add Element2, then clicking on Element2, and so on until eventually r ...

In the middleware, the request body is empty, but in the controller, it contains content

Below is my server.js file: import express from "express"; import mongoose from "mongoose"; import productRouter from "./routers/productRouter.js"; import dotenv from "dotenv"; dotenv.config(); const app = expres ...

Unit testing for changes in AngularJS $scope variables within the .then() function

I'm currently facing an issue with unit testing a function in my controller. The problem lies in making a $scope variable testable. I am assigning the variable within the .then() block of my controller and need to ensure it is set correctly when the . ...