Converting data from a collection of objects within an object to an array of objects within an array

I am facing a data manipulation challenge and seeking a solution.

I have attempted various mapping methods, but none have been successful.

Below is the input dataset:

   data_input = {
    2000: [{
            _id: 0,
            name: "Jeff",
            value: 130,
            year: 2000
        },
        {
            _id: 1,
            name: "Bill",
            value: 30,
            year: 2000
        }
    ],
    2001: [{
            _id: 0,
            name: "Jeff",
            value: 20,
            year: 2001
        },
        {
            _id: 1,
            name: "Bill",
            value: 100,
            year: 2001
        }
    ]
 }

The desired outcome should be as follows:

   data_output = [{
        year: 2000,
        year_data: [{
                _id: 0,
                name: "Jeff",
                value: 130
            },
            {
                _id: 1,
                name: "Bill",
                value: 30
            }
        ]
    },
    {
        year: 2001,
        year_data: [{
                _id: 0,
                name: "Jeff",
                value: 20
            },
            {
                _id: 1,
                name: "Bill",
                value: 100
            }
        ]
    }
 ]

Answer №1

You might consider using Object.entries along with map

The concept here is :-

  • Utilize object.entries to extract key value pairs from an object and map through them to transform the data
  • Key represents the year property in the desired structure, while value corresponds to year_data

let data = {2000: [{ _id: 0, name: "Jeff", value:130, year: 2000 }, { _id: 1, name: "Bill", value:30, year: 2000 } ] , 2001 : [{ _id: 0, name: "Jeff", value: 20, year: 2001 }, {_id:1, name: "Bill", value: 100, year: 2001 } ]}

let final = Object.entries(data).map(([year, year_data]) => ({ year, year_data: year_data.map(({year,...rest})=>rest)}))

console.log(final)

Answer №2

To extract the year from the rest of the object, you can utilize mapping and destructuring of values.

var data_input = { 2000: [{ _id: 0, name: "Jeff", value: 130, year: 2000 }, { _id: 1, name: "Bill", value: 30, year: 2000 }], 2001: [{ _id: 0, name: "Jeff", value: 20, year: 2001 }, { _id: 1, name: "Bill", value: 100, year: 2001 }] },
    result = Object
        .values(data_input)
        .map(a => ({ year: a[0].year, year_data: a.map(({ year, ...rest }) => rest) }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

give this a shot

 data = {
    2000: [{
            _id: 0,
            name: "John",
            value: 150,
            year: 2000
        },
        {
            _id: 1,
            name: "Sarah",
            value: 50,
            year: 2000
        }
    ],
    2001: [{
            _id: 0,
            name: "John",
            value: 50,
            year: 2001
        },
        {
            _id: 1,
            name: "Sarah",
            value: 80,
            year: 2001
        }
    ]
 }

var newData = Object.keys(data).map(key => {
  let yearValues = data[key].map(item => {
    delete item.year
    return item
  });
  return {
    year: key,
    values: yearValues
  }
});

console.log(newData);

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

Unnecessary socket.io connection in a React component

Incorporating socket.io-client into my react component has been a learning experience. Most tutorials recommend setting it up like this: import openSocket from 'socket.io-client'; const socket = openSocket('http://localhost:8000'); In ...

How can I efficiently remove elements from the end of an array in Vue.js?

Is there a way to splice data starting from the back with a higher index? When clicking on the .delete div, how can I make it so the .image-box div deletes starting from the end? I need help implementing this feature in my code. Here is a snippet: < ...

Guidance on handling JSON data containing both nested and non-nested structures

Within file 1, the JSON element "image" is nested in a structured format: {"id": "0001", "type": "donut", "name": "Cake", "image":{"url": "images/0001.jpg", "width": 200, "height": 200}} Spark successfully infers the schema from the data: val df1 = spar ...

Tips for extracting information from a URL and processing it on a webpage

Looking to pull data from a website using AngularJS. My main project is to create a "shipping cart" page. The resource provided is a URL leading to a webpage with information on a specific product. I need to extract this data and integrate it into my pag ...

Problem encountered with the JavaScript for loop failing to execute consistently on each iteration

Currently, I am working on a JavaScript code that alerts the count in an array of pages. The variable urls represents an array of page names, while count contains the count value. My goal is to alert the count value for each page in the urls array. Howe ...

The page refreshes when the anchor element is clicked

Currently, I am working on enhancing a web application that is built on the foundation of traditional aspx (asp.net) web forms with elements of Angular 6 incorporated into it. My current assignment involves resolving a bug that triggers a page refresh whe ...

Reading data from Firestore in Next.js

I came across a Next.js starter that retrieves data from Firestore v9, but it only displays the data after a click event. How can I modify this code in Next.js to automatically show the data without needing to click? import { db } from '@/lib/firebase ...

Learn the process of extracting various data from a PHP source and saving it in select options through AJAX

One of the features on my website is a select option that allows users to choose a hotel name obtained from a dynamic php script. Once a hotel is selected, another select option displays room types available based on the chosen hotel. However, there seem ...

Is there a way to automatically fill in a text field when an option is chosen from a dropdown menu populated with a list of objects?

When working with a DTO that has attributes id, name, and text, I am creating a list of these DTOs and passing them to my JSP using model.addAttribute. In the JSP, I am rendering a Spring list in the following way: <form:select path="notificationsId" i ...

I would like to add a border at the bottom of each item in a ul list

My current focus is on making my website responsive with a breakpoint set at 576px I am aiming to achieve the design shown in this image without any space in the border-bottom and have both elements expand to full width: menu li hover However, I'm c ...

Error message: UnhandledPromiseRejectionWarning in (Node.js, Express.js, MongoDB) - TypeError occurs when trying to access an undefined 'username' property

I'm struggling to fetch and print the post's author from mongodb using client-side code. Unfortunately, my current code is throwing an error. It is a fullstack javascript code and despite my efforts in searching for a solution, I couldn't fi ...

Guide to integrating the Braintree API with Node.js

I am trying to implement Braintree for website payment gateway, but I encountered an issue while following the online guidelines. The code seems to be incompatible with Node.js. Am I missing something? Index.js: //send token to clients app.get("/client_t ...

Adding an object to an array using the Array.push() method deposits an array

Currently, I am extracting the days of absence of my colleague from excel files and storing them in a MongoDB database using Mongoose and Express.js. The process of reading the data is smooth; however, when trying to update the data in the database, an un ...

What causes Python to unpredictably eliminate numbers from an array?

I am currently tackling a challenging issue on HackerRank.com that requires devising a solution capable of handling arrays of varying sizes, ranging from 10 integers to as many as 99,000 integers. To view the problem, visit -> The Challenge To put it ...

Getting a "SyntaxError: Unexpected end of input" error while using jQuery ajax with valid JSON

The PHP response in JSON format shows: {"success":0,"message":"Error: No entityId passed!"} However, my JavaScript code throws an error "SyntaxError: Unexpected end of input". PHP: ... //check if an image id was passed for removal in the POST ...

Execute a JavaScript function when an HTML list element is clicked

As a beginner in web development, I have a question that might seem obvious to some. I want to create a menu where each item, when clicked, triggers a JavaScript function with the item's ID as an argument. I plan to display the menu items in an unorde ...

Guide on linking JSON information to a personalized class

I'm looking to bind the Json response below to a custom class. As I'm new to json, I would appreciate any guidance on how to accomplish this. {"status":"success", "studentInfo":{"RegNo":"ABCD","ID":"123", "parentsDetails":[ {"Parent_ ...

What is the best way to decrease the border width of a chartjs doughnut chart?

I have a vision for my chart based on the mockup: However, here is what I've been able to achieve using chartjs so far: This is the code I'm working with: datasets: [ { data: [3, 8, 13, 9, 2], backgroun ...

Looking to crop a canvas without changing its dimensions using jQuery

I'm currently working on a project that involves overlaying two images; one uploaded by the user and the other a default image. However, I am facing an issue when the uploaded image is a rectangle instead of a square, causing the canvas to resize it. ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...