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

The variables $invalid and $valid in my AngularJS form have not been assigned any values

I came across a post on StackOverflow discussing the issue of both "myForm.$valid" and "myForm.$invalid" being undefined on an Angular form. However, my problem is slightly different. I have defined a form like this: <form name="EntityForm" role="form ...

Dividing image styles within css

I am trying to incorporate 4 arrow images into a CSS class (up, down, right, left). I started with a basic arrow css class: .arrow { background-repeat: no-repeat; background-position: center; } Next, I created subclasses like: .arrow .up { ...

Calculating the total sum of values in a table using Jquery

Can anyone help me calculate the sum of input values from a table using HTML and jQuery? Here is my current code: HTML: <tr id='saved1'> <td><input class='qty'/></td> <td><input class='price&apo ...

Is it possible to mimic a ref attribute with jest/rtl within a functional component?

I'm currently facing an issue with a functional component that includes a helper function. function Component() { imgRef = useRef(null) function helperFunction(node, ref) { if (!ref || !ref.current) return; ...do someth ...

Deleting images based on their class through a loop

Currently, I am in the process of constructing a carousel using data retrieved from an endpoint. The challenge I face is determining the appropriate image size to request from the server. To address this, I perform some front-end processing to dynamically ...

Tips for simulating the $timeout service with sinon?

I am looking to write a unit test for a method within an Angular controller that uses the $timeout service. However, I have been advised not to use inject in this scenario. Therefore, I need to mock $timeout on my own. Can someone guide me on how I can a ...

Tips for managing input for objects in Vue when the object hasn't been declared yet?

<input type="text" v-model="object[obj]"> Output: object:{'obj1':value} Desired outcome after input is added: object:{'obj1':{'prop1':value,'prop2':value}} <input type="text" ...

What is the proper way to indicate the pointer to the current element within the array?

How can I modify a code that displays a list of posts? import React from "react"; type respX = { "id": any, "userId": any, "title": any, "body": any, } interface PropsI { } interface StateI { data: respX []; } export class Compone ...

Customize Bottom Navigation Bar in React Navigation based on User Roles

Is it possible to dynamically hide an item in the react-navigation bottom navigation bar based on a specific condition? For example, if this.state.show == true This is what I've attempted so far: const Main = createBottomTabNavigator( { Home: { ...

When trying to convert to JSON in node, the process fails. However, the data can still be

I am currently working on converting an array to JSON in order to send it to a client. The data I see in the console is as follows: [ NL: [ true, true, true, true, true, true, true, true, true, true, true, true ], ...

I am facing an issue with the routing functionality in the Quasar framework for Vue 3

I seem to be having an issue with my code where no matter what route I give, it only takes me to the home page. Specifically, when I give the path "auth", it still redirects me to the home page. Can someone please help me understand why this is happening a ...

The router should display a component based on the user's access level, even if they are

I'm working on a scenario where the home route needs to cater to both admin and user roles. Is there a way to dynamically display the UserComponent if logged in as a user, and show the AdminComponent if logged in as an admin? This is my current setup ...

What is the best way to send a populated custom class from JavaScript to a .NET MVC app using AJAX?

I am working with a .NET class in C# called BusinessModel: public class BusinessModel { public string BlobName { get; set; } public string NewName { get; set; } } In my MVC Ajax Controller, I have an action called DoBusiness: [HttpPost] public A ...

The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here? Objective: My goal is to fet ...

Incorporating Content-Disposition headers to enable the file to be both downloaded and opened

I'm having trouble allowing users to both view and download files on a web page. I've tried setting headers and using JavaScript, but can't seem to get it right. My goal is to have an HTML page with two links for each file - one to open in ...

Ways to update the color of the mat-dialog-title using the material theme

Currently, I am utilizing the Angular Material Dialog and have been attempting to dynamically change the title color of the dialog based on the material theme. <h1 mat-dialog-title color="primary">{{ title }}</h1> Even though setting ...

Issues with retrieving the output of a function nested within another function through an ajax request

I am attempting to use jQuery to add the results of an ajax call to a paragraph. My goal is to extract the "myResult" variable from the inner getResult function and transfer it to the outer buildParagraph function. Unfortunately, the returned value is und ...

Troubleshooting video streaming loading issues caused by 404 errors in URL paths with videojs

I've been successfully using the video.js library to stream live video. Everything was going well until after a while, the URL started throwing a 404 error during streaming, causing the entire player to get stuck on loading. Now I'm looking for a ...

Establish a cookie using the PHP session's username

I have successfully implemented a general cookie for a one-time use scenario. However, I now need to create a cookie based on the username so that a message is displayed only once per user. My approach involves setting up a PHP session for the username ass ...

Issue with burger menu functionality, button unresponsive

Two files are involved in this issue, one is a Vue file and the other is a JavaScript file. The JavaScript file contains an array and the problem is being described in the console. Additionally, there may be an issue with items as sometimes the same error ...