A guide on converting nested arrays of objects in JavaScript

I am faced with transforming an array of Objects that contain a nested structure. Here is an example of the data:

 [
      {
        geography: 'Austia',
        product: 'RTD Coffee',
        dataType: 'Off-Trade rsp (curr/con, local)',
        timeSeries: [
          {
            year: 2017,
            value: 0.148891823777856,
            highlight: 1,
          },
          {
            year: 2018,
            value: 0.148965642232877,
            highlight: 1,
          },
          {
            year: 2019,
            value: 0.149039460687898,
            highlight: 1,
          },
          {
            year: 2020,
            value: 0.149113279142919,
            highlight: 1,
          },
          {
            year: 2021,
            value: 0.149187097597941,
            highlight: 1,
          },
          {
            year: 2022,
            value: 0.149260916052962,
            highlight: 1,
          },
        ],
      },...
    ];

My goal is to transform this data into a new pattern where the TimeSeries array objects' properties are extracted and mapped to the top level like this:

[
  {
    geography: 'Austria',
    product: 'RTD Coffee',
    dataType: 'Off-Trade rsp (curr/con, local)',
    2017: 0.148891823777856,
    2018: 0.148965642232877,
    2019: 0.149039460687898,
    2020: 0.149113279142919,
    2021: 0.149187097597941,
    2022: 0.149260916052962,
  },
]

Does anyone know how I can achieve this transformation?

Answer №1

Check out this solution

UPDATE: shoutout to @geoffrey for the help

function processYearData(dataArr) {
  return dataArr.map(({yearData, ...rest}) => {
    const yearValues = yearData.reduce((acc, curr) => {
        acc[curr.year] = curr.value
        return acc
    }, {})
    return {...rest, ...yearValues}
  })
}

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

Tips for optimizing iframe loading times using the onload event

I am facing an issue with the timing of iframe loading while using a list of URLs as sources. I have created a child iframe and appended it to the DOM, then run the onload function for further processing. However, the time recorded for each iframe seems in ...

Having trouble updating text in a PDF using NodeJS and hummus library

How can NodeJS be used to replace a string in a PDF file? offers a solution for text replacement in a PDF document. However, when applying the same code, an issue arises where the replaced text is visible in the source code of the PDF but does not render p ...

Exploring the process of navigating between pages in Next.js using react-router-dom

Whenever a successful login occurs, I want to redirect the user to a different page. However, I am encountering an error message: https://i.sstatic.net/Wi8XW.png This is the snippet of code that is causing the issue: export default function SignUp() { ...

Rotate an array of sequential numbers using mathematical calculations

Imagine you have a group of numbers within a certain range, such as: [-4,4] Let's say these numbers are arranged in an array, sorted in numerical order, like this: [-4, -3 -2, -1, 0, 1, 2, 3, 4] Now, if I want to establish a new central point for ...

The versions of my npm and node are not compatible, despite using nvm

I have recently started working with node and npm. I need to run a program repository for my job, which requires compatibility with node version 10.13.0 or even 8.11. I attempted to install nvm, but now every time I try to execute any npm command (includ ...

How can I transform this in JavaScript so that it returns a Promise?

Currently, I am trying to implement code that I found in a SaaS's example. The goal is to retrieve the correct URL for a specific action. The sample code provided by the SaaS looks like this, but I would like to modify it so that it returns a Promise ...

The countdown value in Javascript is not being reset when clearInterval is called

Currently, I am working on implementing a swiper slider with a countdown feature that resets its value every time a slide change occurs. The countdown should restart when the next slide is displayed automatically. However, I have encountered an issue where ...

Would it be unwise to send an AJAX post request every two seconds?

Is it frowned upon or risky to use an AJAX $.post call (with jQuery) to a php file in order to update a specific parameter or number? $.post(file.php, {var:var}, function(data){ // do something }, json); In this scenario, only one user on a single page w ...

After subscribing, creating the form results in receiving an error message that says "formgroup instance expected."

I am currently working on a project using Angular 6 to create a web page that includes a form with a dropdown menu for selecting projects. The dropdown menu is populated by data fetched from a REST API call. Surprisingly, everything works perfectly when I ...

What is the best way to add a button click event listener that persists through DOM changes, such as in a single-page application?

I have developed a ViolentMonkey userscript that adds an event listener to a button with the ID #mark-watched. When this button is clicked, it automatically triggers a click on the button with the ID #next-video. This functionality is necessary because the ...

Can you include conditional logic within a switch statement?

I've been using if, else if, and else statements in my code but recently switched to switch statements which have made things much simpler. Now I'm wondering if it's possible to add multiple conditions inside a switch statement, similar to i ...

Can you pinpoint the origin of the circular reference that triggers the error when using JSON.stringify?

I am encountering an issue where passing an object to JSON.stringify is resulting in the error "Converting circular structure to JSON," but I cannot pinpoint the exact reason for this. The object is being passed via server-side node.js. app.get('/&a ...

Trouble executing select query when using a post array containing duplicate values

After a user submits an array of categories, I need to retrieve rates from a table based on the selected categories. So far, this process has been working well. For example: Array Categories: Auto Parts, Bicycles, Biscuits, Ceiling Fans, Blenders, Artwor ...

Creating a message factory in Typescript using generics

One scenario in my application requires me to define message structures using a simple TypeScript generic along with a basic message factory. Here is the solution I devised: export type Message< T extends string, P extends Record<string, any> ...

Troubleshooting the issue with mocking API and creating a regular expression to match the dynamic part of a URL

I am struggling to create a mock for an API that includes dynamic parts in the URL. I attempted to use a regular expression, but it is not functioning as expected. The URL I am trying to mock is: https://example.com/programs/2fcce6e3-07ec-49a9-9146-fb84fb ...

Inspect the TypeScript typings within Svelte documents directly from the terminal

When I run tsc --noemit, it successfully checks for type errors in the codebase. However, I have encountered an issue where it does not seem to check .svelte files. Is there a way to enable this functionality? I can see the type errors in .svelte files wh ...

Different ways to reference a variable in Typescript without relying on the keyword "this" throughout the codebase

Can we eliminate the need to write "this" repeatedly, and find a way to write heroes, myHero, lastone without using "this"? Similar to how it is done in common JavaScript. https://i.stack.imgur.com/TZ4sM.png ...

New parents, same name D3.JS

Currently utilizing d3.js to visualize a tree structure. When parsing the JSON object containing nameOfNode and NameOfParent, encountering an issue when there are two nodes with the same name. Seeking recommendations on the most effective way to address ...

Is there a way for me to locate a forum using a JWT Token?

I am searching for a way to retrieve forums using JWT Token. If a user has created 3 forums, I want to display them in a list. My Request is structured like this : ### http://localhost:8080/forum/getByOwnerID Authorization: Bearer {{adminToken}} Alternat ...

"Unable to move past the initial segment due to an ongoing

My portfolio webpage includes a "blob" and "blur" effect inspired by this YouTube video (https://www.youtube.com/watch?v=kySGqoU7X-s&t=46s). However, I am encountering an issue where the effect is only displayed in the first section of the page. Even a ...