I possess information stored within the array object below, and I aim to transform it into a different array object format

Here is the response I received from my API:

let data = [
  {
    date: '2021-04-27',
    formatted_date: 'Apr 27',
    location: [
      {
        date: '2021-04-27',
        formatted_date: 'Apr 27',
        country: 'India',
        total_views: 6,
        formatted_views: '6',
        total_watch_duration: 115,
        formatted_watch_duration: '0h 1m',
      },
      {
        date: '2021-04-27',
        formatted_date: 'Apr 27',
        country: 'USA',
        total_views: 16,
        formatted_views: '16',
        total_watch_duration: 1195,
        formatted_watch_duration: '0h 1m',
      },
      {
        date: '2021-04-27',
        formatted_date: 'Apr 27',
        country: 'Canada',
        total_views: 16,
        formatted_views: '10',
        total_watch_duration: 1195,
        formatted_watch_duration: '0h 1m',
      },
    ],
  },
  // More data for different dates and locations
];

I would like the information to be structured in the following format with the assumption that if the location is empty, consider the total_views as 0:

 this.geographySeriesData = [
      {
         name: 'India',
         data: [500, 555, 444, 777, 877, 9944, 750],
       },
       {
         name: 'USA',
         data: [10, 1000, 1200, 1000, 1200, 1000, 500],
       }

     ];

Answer №1

If you're looking to convert data, this snippet might come in handy. It may not be the most efficient solution, but it is quite simple and easy to follow. The crucial information can be found within the finalResult variable.

const convertedData = {};

const locations = myData.map(item => item.location).flat();
locations.forEach(loc => {
    convertedData[loc.country] = [];
});
locations.forEach(loc => {
    convertedData[loc.country].push(loc.total_views);
});

const finalResult = Object.keys(convertedData).map(key => ({ name: key, values: convertedData[key]}));

Answer №2

If you want to achieve the specific structure, follow this code snippet:

listOfCountries = []
countryData = {}

dataArray.forEach((item) => {
  item.locations.forEach((location) => {
    if(location.country in countryData){
      countryViewsList = countryData[location.country]
      countryViewsList.push(location.total_views)
      countryData[location.country] = countryViewsList
    } else {
      countryData = Object.assign(countryData, {[location.country]: [location.total_views]})
    }
  })
})

Object.keys(countryData).forEach((key) =>{
  listOfCountries.push({
    name: key,
    data: countryData[key]
  })
})

listOfCountries will have the precise format as requested.

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

Eliminating memory leaks in a React web application

I'm facing an issue in my ReactJS web application with the following code: useEffect(() => { const fetchInfo = async () => { const res = await fetch(`${api}&page=${page}`); setLoading(true); try { const x = awa ...

The functionality of the Ajax form is limited to a single use

Here's how my script is currently looking. Yes, it comes from a plugin. No, I'm not very familiar with ajax. Is there a way for me to make this form refresh and be ready to accept input again after the first submission? <script> jQuery(do ...

What is the proper method for utilizing the "oneOf" keyword in this schema?

Is it possible to have either option A or B, but not both (mutually exclusive)? In Draft 3, I am required to use whatever is available, even though the version on top says 4. This is because when using an array for "required", it throws an error stating t ...

React and Lottie Animation seamlessly synchronized with scrolling movements

I utilized Bodymovin to create various animations and I am hoping to trigger the animation when the scroll reaches that specific point. I have been attempting to find a solution, but unfortunately, I have not been successful. Currently, I am using Gatsby ...

Tips for modifying JSON response using a function

When I call the function buildFileTree, I store its response in a constant variable called data. const data = this.buildFileTree(dataObject, 0); The value of dataObject is: const dataObject = JSON.parse(TREE_DATA); And the content of TREE_DATA is: cons ...

Is it possible to generate an HTML element by utilizing an array of coordinates?

I have a set of 4 x/y coordinates that looks like this: [{x: 10, y: 5}, {x:10, y:15}, {x:20, y:10}, {x:20, y:20}] Is there a way to create an HTML element where each corner matches one of the coordinates in the array? I am aware that this can be done usi ...

Issue with React submit button for posting data is not functioning as intended

My dilemma lies within a Modal component containing a Form and Button. The goal is to trigger a POST request (managed in a separate file) upon the user clicking the button, which will run a simulation using the validated input values. Surprisingly, the onC ...

What benefits does a bundler offer when releasing packages on npm?

After working with Node.js for many years, I recently ventured into publishing my first Node.JS package for a wider audience. Feeling lost at the beginning, I turned to Google for guidance on how to do this specifically for typescript and stumbled upon thi ...

HighCharts fails to display on Polymer webpage

I am working on a project that involves using Polymer alongside HighCharts. Here is the code I have implemented: HTML : <div class="container" layout vertical center> <paper-shadow z="1" class="span-shadow"> <post-card id ...

Utilize the key-value pair from ng-repeat to expand the scope of the expression

In an attempt to utilize the key value from ng-repeat as an extension of another scope.arrayResult, I aim to achieve arrayResult.q1/q2/q3 etc... <ul ng-repeat="(key,x) in data"> <li><h4>Question: {{x}}</h4> <p>{{ ar ...

The POST request from the form is returning a null value

I am currently facing an issue with using post in Express and BodyParser to insert data from a form in an EJS file into MySQL. The data keeps returning null, indicating that it is not being parsed correctly from the form to the backend. Can anyone offer as ...

Optimizing NodeJS for scheduling and sending bulk text messages based on MongoDB data

I am currently developing an application that relies on MongoDB database entries to send text messages through AWS. The information stored in the database includes the message content, phone number, and scheduled time for sending the message. As of now, ...

Having trouble toggling journal entries in an HTML journal? The Jquery function might not be working properly

I have been tasked with creating a civil war journal for my 8th grade Social Studies class and I decided to present it as an HTML file featuring the title and date of each journal entry. The goal is to allow users to click on each entry to open it while au ...

Using the json_decode function with a nested array

Hi everyone, I'm new here and English is not my first language, so please bear with me =) Currently, I am working with the steam-api and facing an issue that I need help with: I have been able to access the JSON data containing descriptions, but now ...

Spring MVC: Incorporating Java Map into Optgroup Options

In my Spring MVC project, I am currently passing a Map from Java to my webpage using the variable "userLocales" through request.setAttribute('userLocales', bluh bluh bluh). I am looking for a way to extract the strings from this variable and use ...

Handling events for components that receive props from various components in a list

In my code, I have a component called PrivateReview which includes event handlers for updating its content. export default function PrivateReview(props) { const classes = useStyles(); const removeReviewAndReload = async () => { await ...

Error: JSON parsing stopped due to unexpected end of file while attempting to parse data

After testing with other APIs successfully, I found that this particular one is not functioning as expected. const express = require("express"); const https = require("https"); const bodyParser = require("body-parser"); const ...

Updating view with *ngIf won't reflect change in property caused by route change

My custom select bar has a feature where products-header__select expands the list when clicked. To achieve this, I created the property expanded to track its current state. Using *ngIf, I toggle its visibility. The functionality works as expected when cli ...

Is it possible to continuously re-render a React Functional Component with Axios and useState/useEffect?

Seeking assistance with creating a React Functional Component using Typescript to fetch data from an API and pass it to another component. However, encountering the error message "Error: Too many re-renders. React limits the number of renders to prevent an ...

Using VueJS to navigate to a specific route and pass parameters along with the

I'm a complete beginner when it comes to VueJS. Can someone please help me figure out how to access the deviceId in the Device component within vuejs? I've noticed that the deviceId in the h1 tag is not displaying on the Device component page. ...