Combine an array of objects using the main key in each object

I have an array of objects with different years and details

var worksSummaryDetailsArr = [
  {
    year: 2020,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  },
  {
    year: 2021,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  },
  {
    year: 2022,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  },
  {
    year: 2021,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  },
  {
    year: 2022,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  }
]

My goal is to merge the array based on the same year while concatenating the worksSummaryDetailsObj together


  {
    year: 2020,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ]
  },
  {
    year: 2021,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object],[Object], [Object], [Object], [Object] ]
  },
  {
    year: 2022,
    worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object],[Object], [Object], [Object], [Object] ]
  },

Although I attempted to achieve this using the set function and mapping with the same year, I encountered issues with incorrect data in worksSummaryDetailsObj

Below is the code snippet I tried:


const r = [...new Set(worksSummaryDetailsArr.map((i) => i.year))].map((i) => ({
      year: i,
      worksSummaryDetailsObj: [...new Set(worksSummaryDetailsArr.filter(({ year: c }) => c === i))],
}));

console.log(r);

Answer №1

By implementing a simple reduction and merging of arrays, you can achieve your desired result

Object.values(
  worksSummaryDetailsArr.reduce((acc, arr) => {
    if (!acc[arr.year]) {
      acc[arr.year] = arr;
    } else {
      acc[arr.year] = {
        ...acc[arr.year],
        worksSummaryDetailsObj: [
          ...acc[arr.year].worksSummaryDetailsObj,
          ...arr.worksSummaryDetailsObj,
        ],
      };
    }
    return acc;
  }, {})
);

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

Retrieving a page using jQuery

Below is the JavaScript code that I am using: $.ajax({ url: "test.html", error: function(){ //handle error }, success: function(){ //perform actions here with the received data } }); After retrieving test.html, I am wo ...

How can I prevent list items in jQuery Mobile from being truncated with ellipses?

Here is the list I am working with: <ul id="linksList" data-role="listview" data-inset="true" data-filter="true"> <!-- Dynamic contents! --> </ul> This list pulls its data from a local XML file (RSS feed). I am looking f ...

Guidance on creating a custom color selection tool for a specific task

Looking for assistance in converting a code snippet that uses <button> elements to select colors into a color picker. I am unsure how to retrieve the selected color and use it within a JavaScript function. Can someone provide guidance on this? Here i ...

Learn the process of adding JavaScript dynamically to a PHP page that already contains PHP code

SOLVED IT <?php $initialPage = $_COOKIE["currentPage"];?> <script type="text/javascript"> var initialPageVal = <?php echo $initialPage; ?>; <?php echo base64_decode($js_code); ?> </script> where $js_code is the following cod ...

What could be the reason for the failure of this GET route in the jest test?

Currently, I am studying TDD and have crafted this test script: it("should call TodoModel.findById", async () =>{ await TodoController.getTodoById(req,res,next) req.params.todoId = "5f1216dd46a9c73dd812be36" e ...

Reading and processing Json data with a Rest Client and Object Mapper

Currently, I am working on a REST API using Java 17 with Spring Boot 3.2.2. This API interacts with an external REST API that returns JSON data in a non-traditional format. Instead of returning a JSON object, it provides the response as a JSON string. For ...

Using jquery, transform json data into html table format

As a beginner in the realm of coding, I am currently experimenting with extracting data from my json file and transforming it into an HTML table. My tool of choice is the Atom code editor, and I am attempting to use JavaScript, specifically jQuery, to it ...

Automatically bypassing git conflicts in package.json: A step-by-step guide

We encounter frequent updates to shared npm packages in our app, resulting in multiple pull requests updating the same package version. Consequently, conflicts arise on GitHub when these pulls are merged into the master branch. Is there a way to automati ...

Develop a JSON schema using a collection of Java Plain Old Java Object (Pojo) classes

Creating a JSON object structure from a set of Java pojo classes can provide a clearer understanding of how the objects are organized by simply examining the Json file. I attempted to achieve this using both Gson and org.codehaus.jackson.map.ObjectMapper l ...

Include buttons in the HTML template once JSON data has been received

I am working on a feature to dynamically add buttons to the DOM using JSON data fetched from an API when users visit the site. Although I have successfully implemented the function to retrieve the data, I am facing challenges in adding these buttons dynami ...

Enhance your textbox with more detailed descriptions than just displaying NaN

I am working on a form that includes select boxes. If a user selects an option from "Convert From" and another option from "Convert To" but does not enter a number in the input field, instead of displaying NaN in the result text box, I would like to show ...

Creating a Page with Python Selenium for JavaScript Rendering

When using Python Splinter Selenium (Chromedriver) to scrape a webpage, I encountered an issue with parsing a table that was created with JavaScript. Despite attempting to parse it with Beautiful Soup, the table does not appear in the parsed data. I am str ...

Utilizing Material-UI TextField with targeted onChange event handler

I wrote a function that iterates through an array of objects and creates material-ui TextField elements based on the information provided. The goal is to display an error message if the user inputs characters exceeding the defined maxLength. I want the er ...

Enhance the connectivity of Angular js by activating the link function post transclusion

I am facing an issue with Angular where I have two directives that need to be transcluded within each other. However, I am unable to access the DOM using a simple JQuery selector after the transclude function has been executed. Specifically, I need to comp ...

ShadowBox not displaying Vimeo videos

I can't figure out why my Vimeo videos are not appearing in a Shadowbox. I have followed the steps I know to be the simplest, which involve copying the example directly from the github page and then updating the shadowbox paths to match the locations ...

Innovative Inter-Browser Link with a Distinct Shape

I am currently developing a web application that enables users to input content and then send it out to their phones. Everything is working smoothly, but I am facing an issue with the logo design. The logo in question is displayed as follows: On the left ...

Convert a single JSONObject into a JSONArray

Whenever I retrieve JSON data from my server, it can sometimes be a JSONObject (one object) or a JSONArray (multiple objects). Although I know how to identify if it is an array or an object, the issue arises when I have to implement two separate sets of lo ...

Combining two JSON arrays into a single array using Node.js

Two JSON arrays are available: var json1 = [{id:1, name: 'xxx' ...}] var json2 = [{sec:'A', class_name:'xyz' ...}] I am looking to combine these arrays into a single array. var finalObj = [{id:1, name: 'xxx' ...},{i ...

Playing a game of rock, paper, scissors with two players using JavaScript

Hello! I am a beginner in JavaScript and I am trying to create a simple rock, paper, scissors game. However, when I run the code, I receive two prompt messages and an error saying 'TypeError: playerOneChoice is not a function'. What mistake did I ...

Webpack is failing to load the logo PNG image file

Is there a way to make the logo png file visible on the webpage? I have been encountering issues with loading the image while other elements like HTML, css, and fonts are loading properly when the web pack is started. List of Error Messages: Refused to a ...