Reformat an array containing objects so that their structure is changed to a different format

Imagine a scenario where the data needs to be manipulated into a specific format called 'result' for easier display on the user interface. In this 'result', the month numbers are used as keys, representing each month's quantity.

const data = [
            { date: '10/1/2021', quantity: 47 },
            { date: '11/1/2021', quantity: 58 },
            { date: '12/1/2021', quantity: 96 },
            { date: '1/1/2022', quantity: 88 },
            { date: '2/1/2022', quantity: 90 },
        ];

const result = [
            { year: 2021, 10: 47, 11: 58, 12: 96 },
            { year: 2022, 1: 88, 2: 90 }
        ];

I've managed to generate an 'intermediate' structure from the original data but I'm struggling with converting it into the final 'result' format efficiently using ES6 methods.

const data = [
    { date: '10/1/2021', quantity: 47 },
    { date: '11/1/2021', quantity: 58 },
    { date: '12/1/2021', quantity: 96 },
    { date: '1/1/2022', quantity: 88 },
    { date: '2/1/2022', quantity: 90 },
];

const intermediate = data.map(o => {
    // eslint-disable-next-line no-unused-vars
    const [month, day, year] = o.date.split('/');    // destructuring assignment
    return { year: year, [month]: o.quantity }
});

console.log(intermediate);

Answer №1

Modified: changed intermediate to result

const result = [
  { '10': 47, 'year': '2021' },
  { '11': 58, 'year': '2021' },
  { '12': 96, 'year': '2021' },
  { '1': 88, 'year': '2022' },
  { '2': 90, 'year': '2022' }
]

const yearDataMap = {}
result.forEach(dto => {
  const storageObj = {} // temporary object for storing data

  Object.entries(dto).forEach(([key, value]) => { 
    if(key === 'year') {
      storageObj['year'] = value
    }else {
      storageObj['month'] = key
      storageObj['quantity'] = value
    }
  })

  const {year, month, quantity} = storageObj 

  if (!yearDataMap[year]){ 
    yearDataMap[year] = { year } 
  }

  yearDataMap[year][month] = quantity
})

const yearsArr = Object.values(yearDataMap)

console.log(yearsArr)

Changed given to result:

const data = [
  { date: '10/1/2021', quantity: 47 },
  { date: '11/1/2021', quantity: 58 },
  { date: '12/1/2021', quantity: 96 },
  { date: '1/1/2022', quantity: 88 },
  { date: '2/1/2022', quantity: 90 },
];

const yearDataMap = {} 

data.forEach(dto => {
  const {date, quantity} = dto
  const [month, day, year] = date.split('/')

  if (!yearDataMap[year]){ 
    yearDataMap[year] = { year } 
  }

  yearDataMap[year][month] = quantity 
})

const yearDataArr = Object.values(yearDataMap) 

console.log(yearDataArr)

Answer №2

your approach wasn't too shabby. I took your foundation and expanded upon it with the aim of populating a global object. That was the ultimate objective.

globalData = {}
info = [
  { date: '10/1/2021', amount: 47 },
  { date: '11/1/2021', amount: 58 },
  { date: '12/1/2021', amount: 96 },
  { date: '1/1/2022', amount: 88 },
  { date: '2/1/2022', amount: 90 },
];

info.forEach((entry) => {
  [month, day, year] = entry.date.split('/'); 
  
  if (!globalData[year]) {
    globalData[year] = { year }    
  }
    globalData[year][month] = entry.amount    
})
const finalResult = Object.values(globalData)
console.log(finalResult)

Answer №3

A method to transition from starting point to final outcome:

const info = [
    { time: '10/1/2021', count: 47 },
    { time: '11/1/2021', count: 58 },
    { time: '12/1/2021', count: 96 },
    { time: '1/1/2022', count: 88 },
    { time: '2/1/2022', count: 90 },
];

const startingPoint = info.map(obj => {
    // eslint-disable-next-line no-unused-vars
    const [month, day, year] = obj.time.split('/');    // destructuring assignment
    return { year: year, [month]: obj.count }
});

let yearsArr = [...new Set(startingPoint.map(o => o.year))];
let dataAccumulator = Object.assign({}, ...yearsArr.map(year => ({[year]: {}})));

startingPoint.forEach(obj => {
    dataAccumulator[obj.year] = { ...dataAccumulator[obj.year], ...obj };
});

const finalOutcome = Object.values(dataAccumulator);
console.log(finalOutcome);

However, the above process included more steps than necessary. Eventually simplified it to -

const info = [
    { time: '10/1/2021', count: 47 },
    { time: '11/1/2021', count: 58 },
    { time: '12/1/2021', count: 96 },
    { time: '1/1/2022', count: 88 },
    { time: '2/1/2022', count: 90 },
];

resultantData = {};

info.forEach(obj => {
    // eslint-disable-next-line no-unused-vars
    const [month, day, year] = obj.time.split('/');    // destructuring assignment
    resultantData[year] = { ...resultantData[year], year: year, [month]: obj.count };
});

const finalOutcome = Object.values(resultantData);
console.log(finalOutcome);

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

Trigger an instantaneous update of the masonry grid

My website currently utilizes a script that generates a grid, and the grid elements are automatically adjusted each time the width of the viewport is modified. Although I do not have access to or control over the script since I did not write it myself, I s ...

What is the best way to save javascript code without running it?

I've been attempting to insert AdSense JavaScript code into a specific div location using jQuery, but it appears that the JavaScript code does not function well inside a jQuery variable. It gets executed instead. Despite trying to encode it with PHP&a ...

Optimal methods for handling Ajax requests in the present day

Recently, I revisited some websites I co-built with a friend and was working on getting them functional again. It's been a while since I've done any AJAX work, and I'm realizing that there aren't many resources available to help trouble ...

Experiencing memory issues with small programs in Node on macOS?

Currently, I am in the process of learning JavaScript and making use of node to execute JS programs directly from the terminal using this command: node program1.js The issue that I am encountering involves a simple JavaScript program that is supposed to ...

What is the best way to keep my data within a global variable?

$(function(){ let spaceTravelersData; $.getJSON('http://api.open-notify.org/astros.json', retrieveData); function retrieveData(data) { spaceTravelersData = data; } alert(spaceTravelersData.people[0].name) }); I a ...

Transmitting information from JavaScript to a PHP script

I am currently using a function that grabs text from a PHP file on our server and inserts it into an HTML page. However, I now need to modify this function in order to SEND data (specifically a couple of JavaScript variables) to the PHP file instead of si ...

Django issue: A Tuple or struct_time argument is necessary

Currently, I am developing a code that deals with 2 variables - showdate and viewtype. Both of these variables are transferred via JavaScript using the POST method. viewtype = send an srt showdate = send a date from javascript Within this code snippet, ...

Retrieve JSON data within an HTML element, where the element is sourced from an AJAX GET response

What is the best way to extract JSON data from the response below? $.get('http://localhost:8000/json', function(response) { alert(response); }); The response is as follows: <div id="dom-target" style="display: none;"> {"logo":"log ...

What is the best way to store the result from a JavaScript FileReader into a variable for future reference?

I am currently facing an issue uploading a local .json file to my web application. I have managed to display the file in the dev tools, but I am unable to make it accessible for further use. It seems like the problem lies in how I handle (or fail to handle ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

You can only use the angularjs http function once

After browsing through similar forum posts, I was unable to find a solution to my issue. It could be due to my limited experience with JavaScript and Angular. Here's the problem: Desired Outcome: When I click a button, I want the data from the server ...

What could be causing my page width to only expand to 100% when using "fit-content"?

After searching extensively, I'm unable to find a solution that fits my current issue. My goal is to construct a practice ecommerce website using React. One of the components I have is a header which I'd like to occupy 100% of the screen width, c ...

Bootstrap: Retrieve an image from a modal

I am working on a modal that contains a variety of selectable images. When an image is clicked, I want to change the text of the button in the modal to display the name of the selected image. Additionally, I would like to grab the selected image and displa ...

The text/font-weight of the header button is mysteriously shifting without warning

While creating a header for my webpage, I encountered an issue where the text family was changing when the dropdown menu was launched in Safari 8. Curiously, this behavior did not occur when using Chrome to launch the jQuery function. Even after attempting ...

Is it possible to assign a property name using a string during the creation of an object?

Can an object property be named directly within the object declaration instead of afterwards? For example, this syntax works: var name = "foo"; var obj = {}; obj[name] = "bar"; // obj.foo === "bar" But is there a way to define it inside the object it ...

Using JavaScript to extract data from a JSON-formatted URL

I am currently facing a challenge with parsing JSON data from a specific URL. Despite my efforts, I am unable to retrieve any information related to the "ask" and "bid" values from this JSON feed. The URL in question is . The structure of the JSON data is ...

Stop the continuous AJAX loop or look for an alternative method to retrieve and compare a list of HTML pages

I am in need of a solution to insert a small script onto all of my website pages. The script must include the correct token for each of the 21 different domains I have. However, not all the sites are directly under the 'domain name' but are consi ...

Steps to create a personalized material-ui element

I am looking to create a custom time duration component by modifying the TextField component. https://i.stack.imgur.com/fLsFs.png https://i.stack.imgur.com/SdpdH.png If anyone has any advice or assistance, it would be greatly appreciated. Thank you! ...

Updating state using the react `setState()` function will automatically trigger a re-render

I am currently working on a large form using React and material-ui. The form implements two-way binding to update the state when input changes occur. Interestingly, changing any input field triggers updates in all components (as observed through TraceRea ...

When I click on .toggle-menu, I want the data-target to have a toggled class and the other divs to expand

Looking to achieve a functionality where clicking on .toggle-menu will toggle a class on the specified data-target element and expand other divs accordingly. jQuery(document).ready(function() { var windowWidth = jQuery(window).width(); if (win ...