Converting the structure of an object into an array structure for highcharts can be achieved through

I am looking to transform the object structure below:

     [
        {
            "tahun": "2010",
            "apel": 100,
            "pisang": 200,
            "anggur": 300,
            "nanas": 400,
            "melon": 500
        },
        {
            "tahun": "2011",
            "apel": 145,
            "pisang": 167,
            "anggur": 210,
            "nanas": 110,
            "melon": 78
        }
     [

into this array structure for my highchart in Django,

[
 ["2010",100],
 ["2010",200],
 ["2010",300],
 ["2010",400],
 ["2010",500],
 ["2011",145],
 ["2011",167],
 ["2011",210],
 ["2011",110],
 ["2011",78]
]

Any suggestions on achieving this transformation, perhaps using AJAX?

Answer №1

To transform a list of dictionaries into a list of lists on the server side, you can use the following code snippet:

>>> data = [{'year': '2010', 'apple': 100, 'banana': 200, 'grape': 300, 'pineapple': 400, 'watermelon': 500}, {'year': '2011', 'apple': 145, 'banana': 167, 'grape': 210, 'pineapple': 110, 'watermelon': 78}]
>>> [[x['year'], x['apple']] for x in data]
[['2010', 100], ['2011', 145]]

Answer №2

If you need to simplify the original format into a different structure, you can achieve that using the following method:

const data = [
  {
      "year": "2010",
      "apple": 100,
      "banana": 200,
      "grapes": 300,
      "pineapple": 400,
      "melon": 500
  },
  {
      "year": "2011",
      "apple": 145,
      "banana": 167,
      "grapes": 210,
      "pineapple": 110,
      "melon": 78
  }
];

const result = data.reduce((prev, curr) => {
  const year = curr.year;
  delete curr.year;
  return [...prev, ...Object.keys(curr).map(key => [year, curr[key]])];
}, []);

It may not be the most elegant solution, but it gets the job 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

Guide on implementing the 'cut' feature using electron-localshortcut

Looking for a way to use keyboard shortcuts on Mac without relying on the menu? I recently came across this helpful post: Is it possible to create non-global accelerators without adding them to a menu? Thanks to this informative article, I learned about ...

Is there a method in Angular to refresh or recompile a specific section or entire page that utilizes one-time bindings?

With numerous lists on our page containing potentially hundreds of items, we prioritize performance by implementing one-time bindings to update only when necessary and minimize the number of watchers. If we decide to utilize one-time bindings, is there a ...

Working with JSON objects in AngularJS

I have a JSON dataset in the following structure. I need to extract information from the JSON and display it on an HTML table. [region: [name:"", code:""IntradayBalance:{ currency:,Time:,Balance: }.... ], acccountcurrencyBalance:[{ c ...

Can someone explain the process of unescaping characters in an API response to me?

I have created an application that leverages AngularJS to pull data from the WP Rest API V2. The response includes escaped characters, like the example below: "excerpt": { "rendered": "<p>When we go shopping, we encounter many different labeling ...

Tips on cycling through hovered elements in a specific class periodically

I'm looking to add a hover animation to certain elements after a specific time, but I haven't been able to make it work correctly. Here's my attempted solution: CODE $(document).ready(function(){ function setHover() { $(' ...

What is the origin of the second parameter in an arrow function that returns another arrow function in a React component with Redux?

I'm having trouble understanding where the (val) parameter is coming from in the returned arrow function. I understand that max/minLength is an arrow function taking an argument set on the input field (3 and 25), and it returns another arrow function ...

Validating Input Field with Regular Expression in JavaScript/TypeScript to Avoid Starting with Zero

I need to create a RegEx for a text field in Angular / TypeScript that limits the user to inputting only a 1-3 digit number that does not start with 0. While it's straightforward to restrict input to just digits, I'm struggling to prevent an inpu ...

Error: The absence of an element identified by the locator does not cause the protractor spec to fail, but rather it executes successfully

This automation framework follows the page object model and utilizes the async/await approach rather than promises. TypeScript is used, with compilation to JavaScript (protractor) for script execution. Page Object: async addProjectDetails(): Promise< ...

ActivatedRoute not receiving the parameter value

Having trouble retrieving the parameter from the route and passing it to a function within the component which then communicates with the service. Initially tried placing the parameter retrieval in the NgInit but moved it to the constructor, still no succ ...

Tally up the occurrences of each item in the array and provide the result in the form

Is there a built-in method in JavaScript to convert an array like: const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black']; into an object that c ...

Modifying SASS variable values based on the presence of specific text in the page URL

How can I utilize the same SASS file for two different websites with similar functionality but different color schemes? My goal is to dynamically change the color based on the URL of the page. However, I am facing challenges in extracting the page URL from ...

retrieve dynamically generated content following successful login using cURL

It's common knowledge that curl doesn't process JavaScript, it only fetches static HTML. This is why a simple curl command won't suffice for my needs. I'm not well-versed in PHP, still new to this field. From what I've gathered so ...

After conducting a filtered search, the data stored in the Datatable disappears

Encountering an issue with a data table; whenever the search function is used, all data is lost as soon as any input is made in the search bar. The data table is dynamically created using AJAX - starting with a request to the server to retrieve data for th ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

JavaScript event in Chrome extension triggers a browser notification and allows for modification using a specific method

I am currently developing a Chrome extension that is designed to take specific actions when system notifications appear, with the main goal being to close them automatically. One example of such a notification is the "Restore pages?" prompt: https://i.sta ...

Avoid having logs displayed on the server end when utilizing console.log commands

Being new to JavaScript and Node.js, I am attempting to have my application output logs on the server side. getUser.onclick = function () { console.log('Server running at http://127.0.0.1:1337/'); var req = new XMLHttpRequest(); r ...

Utilizing Polymer 3 in a different context such as ASP.NET MVC allows for the development of versatile components known as PolymerElements that can be reused

I am currently working on integrating Polymer 3 components into my ASP.NET MVC application. I'm not entirely sure if my approach to this issue is correct at the moment. My main goal is to execute everything from IIS Express. However, I'm encou ...

Executing a Function Following the Completion of getAuth() in React Firebase

I have a function that needs the user id to run properly. However, the function is executing before the getAuth process is completed. const user = getAuth() getDoc(doc(db, 'users', user.currentUser.uid)) When I try to run the above code, it thro ...

Utilize Vue to access and read a file stored in the current directory

I am attempting to retrieve data from a text file that is located in the same directory as my .vue file. Unfortunately, I am encountering an issue where the content of the text file is not being displayed in both Chrome and Firefox. Instead, I am seeing th ...

Update the content retrieved through ajax periodically

Looking to set up a periodic update for this ajax fetch function, say every 10 seconds. I've tried a few approaches but none seem to work as expected. That's why I'm reaching out here for help. So, any idea how I can refresh the content ev ...