What is the best method for transforming JSON containing multiple objects into an array using JavaScript?

I have received a JSON response structured as follows.

[
    {
        "week":1,
        "win":10,
        "lose":[
            {
                "week":2,
                "count":1
            },
            {
                "week":3,
                "count":0
            }
        ]
    },
    {
        "week":2,
        "win":7,
        "lose":[
            {
                "week":3,
                "count":1
            },
            {
                "week":4,
                "count":3
            }
        ]
    },
    {
        "week":3,
        "win":8,
        "lose":[
            {
                "week":4,
                "count":1
            }
        ]
    }
]

My goal is to transform this data into an array with the "win" counts and "count" values nested within the "lose" object. Is there a more efficient solution to achieve this without resorting to for loops?

Expected result:

[

[10, 1, 0],

[7, 1, 3],

[8, 1]

]

Considering that I am working on the front end, what would be the optimal approach to tackle this task?

Answer №1

An efficient solution utilizing two map() functions:

const data = [{
  "week": 1,
  "lost": 10,
  "recovery_timespan": [{
    "week": 2,
    "count": 1
  }, {
    "week": 3,
    "count": 0
  }]
}, {
  "week": 2,
  "lost": 7,
  "recovery_timespan": [{
    "week": 3,
    "count": 1
  }, {
    "week": 4,
    "count": 3
  }]
}, {
  "week": 3,
  "lost": 8,
  "recovery_timespan": [{
    "week": 4,
    "count": 1
  }]
}];

const result = data.map(({lost, recovery_timespan}) => [
  lost,
  ...recovery_timespan.map(({count}) => count)
]);

console.log(result);

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

Include a JSON or object within a string JSON array

Seeking advice on manipulating a string formatted like a JSON array with objects: myJsonArray = "[ {\"name\":\"alex\",\"weight\":\"88\"}, {\"name\":\"Emma\",\ ...

The Bootstrap Modal retains the "display: block" property even when it is hidden

My web app has a bootstrap modal that seems to have a mind of its own. Even when I use myModal.modal('close');, the modal stubbornly stays displayed. It's a strange problem that's really frustrating. Every so often, about one out of te ...

Sending a sound recording to the express js server with the help of multer

I'm currently working on a project where I need to record audio and save it in my local directory (uploads folder) using express js and multer. The recording part is working fine with mic-recorder-to-mp3, but I'm facing an issue with saving the r ...

Rearrange Material UI styles in a separate file within a React project

Currently, I am developing an application utilizing material-ui, React, and Typescript. The conventional code for <Grid> looks like this: <Grid container direction="row" justifyContent="center" alignItems="center&q ...

Persist changes to array even after refreshing the page

Currently, I am utilizing Angular 2 (Typescript) to code my webpage, which features various forms with inputs. Upon submitting these forms, they each trigger a function that adds a new instance of an object based on the inputs to an array. This array is th ...

What is the best way for me to incorporate images retrieved from an API call into my

Hey everyone, this is my first time posting on here so if there's anything I'm missing, please let me know! I've run into an issue with the images on my categories page not aligning properly and being different sizes after I incorporated som ...

Image embedded in Discord

I'm encountering an issue with my discord bot. I'd like the image to be displayed within the embed instead of showing up as a separate message. Can someone help me troubleshoot this problem? Below is the code I'm currently using: function f ...

Tips for distinguishing between the fireauth login callback for Login and signup

Currently, I am developing an angular application that integrates with Firestore. I have incorporated Auth::createUserWithEmailAndPassword() to register a user and Auth::signInWithEmailAndPassword() to log in the user. In both scenarios, the user success ...

Add Firebase Data to Dropdown

Utilizing Vuetify to build a dropdown has been an interesting challenge for me. While I can successfully select a value and store it in the firebase database, I'm facing difficulties when it comes to repopulating the dropdown after page refresh. Belo ...

Problem with JQuery draggable and droppable appending elements

I am looking to create a functionality where a div can be dragged into another droppable div and be contained within it, while still remaining draggable inside the droppable div. However, When I try to drag the div into the droppable area, it seems to be ...

`Get the height of a specific element within a FlatList using the index property in React Native`

I'm currently exploring a workaround for the initialScrollIndex issue in FlatList that is not functioning correctly. I attempted to use getItemLayout to address this, but encountered a new problem - my elements inside the FlatList have varying heights ...

Is conditional CSS possible with NextJS?

While working on an animated dropdown for a navbar, I came across this interesting dilemma. In a strict React setup, you can use an inline if/else statement with onClick toggle to manage CSS animation styles. To ensure default styling (no animation) when ...

Show picture during the process of loading an external webpage

Utilizing a script to load an external page (external meaning a page within my website) inside a div. Loading the page takes time, so I want to display an image until the page is fully loaded. JAVASCRIPT function HideLoader() { $('#loader' ...

What is the best way to conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed docum ...

Validation for dates in Angular.Js input is important to ensure that only

Take a look at this form: <form name="user_submission" novalidate="novalidate" method="post"> <input type="date" name="date_of_birth" ng-focus="save_data()" ng-model-options="{timezone: 'UTC'}" ng-pattern="/^(19\d{2}|[2-9]& ...

Is it possible for Javascript to detect your IP address?

Question About Getting Client IP Address: Get Client IP using just Javascript? I am aware that PHP can retrieve the client's IP address using <?php echo $_SERVER['REMOTE_ADDR']; ?> Is there a way for JavaScript to accomplish the ...

Unable to retrieve XML attributes while iterating through xml2js-parsed JSON items

I'm currently facing a challenge in accessing the attributes of items within an xml rss feed once it has been converted to json using the xml2js package. Although I can access individual attributes with items[0].el.$.attribute, my attempts to delve de ...

node-gallery reports: "No albums were discovered"

I am exploring the use of node-gallery in my Node js/Express/Jade project. After following the guidelines provided at https://github.com/cianclarke/node-gallery, I encountered an issue when attempting to access the page localhost:3000/gallery: {"message" ...

Achieving a collapsing navbar on click in Bootstrap 5

Is there a way to collapse this navigation bar after clicking on a link, without using a JavaScript event listener or the data-bs-toggle and data-bs-target methods mentioned in this article? I tried both methods but they are not working with my code. Here ...

jQuery sidebar with a fixed position

Is there a way to implement a sidebar menu feature using jQuery that reappears on the left as the user scrolls down the page? You can see an example sidebar menu here. ...