Using JavaScript to transform an array of objects into a new array of different objects

This issue has cropped up in various scenarios and programming languages, and I have always managed to find a workaround. However, I am now hoping to establish a proper pattern to address this problem once and for all. It typically arises when joining SQL tables. Instead of making separate calls for items and comments, I know there must be a way to retrieve all the information in a single call and then flatten the result.

My goal is to transform an array structured like this:

[
  {
    itemId: 1,
    comments: {
      commentId: 1
    }
  },
  {
    itemId: 1,
    comments: {
      commentId: 2
    }
  },
  {
    itemId: 2,
    comments: {
      commentId: 3
    }
  }
]

Into the following format:

[
  {
    itemId: 1,
    comments: [
      {
        commentId: 1
      },
      {
        commentId: 2
      }
    ]
  },
  {
    itemId: 2,
    comments: [
      {
        commentId: 3
      }
    ]
  }
]

Answer №1

Here is a solution that should meet your needs:

function mergeArrayItems(arr) {
    var combinedObj = {};

    // Merge the comments
    for (var i=0; i < arr.length; i++) {
        if (combinedObj[arr[i].itemID]) {
            combinedObj[arr[i].itemID].push(arr[i].comments);
        } else {
            combinedObj[arr[i].itemID] = [arr[i].comments];
        }
    }

    // Create the final list
    var keys = Object.keys(combinedObj);
    return keys.map(function(key){return {itemID: key, comments: combinedObj[key]} })
}

Answer №2

You also have the option to utilize the filter() method:

function combineData(data) {
    var dictionary = {};
    return data.filter(function(entry) {
        if (!dictionary[entry.id]) {
            entry.info = [entry.info];
            dictionary[entry.id] = entry;
            return true;
        } else {
            dictionary[entry.id].info.push(entry.info);
            return false;
        }
    });
}

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

Can all anchor tags properties on a website be simultaneously changed?

Recently, I discovered that using target="_blank" in anchor tags can leave a website vulnerable to security risks, and the recommended alternative is to use rel="noopener". In my current web project, all anchor tags are currently utilizing the target attri ...

Disable the ability to select text when double-clicking

Is there a way to prevent text selection on double click while still allowing selection on mouse drag? Whenever I try to remove selection on dblclick or mouseup, it flashes, which is not the desired outcome as shown in this jsfiddle. UPD: I am not lookin ...

Personalized design created using v-for

I have an array being passed through v-for and I want to use the values within the "style" attribute. Essentially, I need to append the value from v-for to style:"left"+EachValue+"px", but I'm having trouble with the syntax. I'm unsure if this ap ...

What is the best way to add checkbox functionality in React with both checked and unchecked states?

Trying to incorporate checkboxes in React has been a bit challenging for me. I am encountering an issue when it comes to checking and unchecking the checkbox. I attempted to use the onchange handler. onChange={() => { // First appro ...

SDK for generating templates with JavaScript/jQuery

I am in the process of developing an SDK in JavaScript/jQuery that can generate templates based on user input, such as profile templates and dialog templates. These templates require data from an AJAX call to be created. User input should include certain ...

Is it possible to implement a setInterval on the socket.io function within the componentDidMount or componentDidUpdate methods

I'm currently working on a website where I display the number of online users. However, I've encountered an issue with the online user counter not refreshing automatically. When I open the site in a new tab, the counter increases in the new tab b ...

Configure your restify REST API server to handle both HTTPS and HTTP protocols

I'm currently utilizing node.js restify version 4.0.3 The code snippet below functions as a basic REST API server supporting HTTP requests. An example of an API call is var restify = require('restify'); var server = restify.createServer( ...

What are some ways to direct users from one page to another without relying on server-side programming?

Is there a way to create a redirect page using jQuery or JavaScript? What is the process of writing client-side scripting code to redirect the browser from one page (page1) to another page (page n)? ...

I am curious about how to switch between different modes in order to change the appearance, functionality, and interaction of a program. Currently, I am exploring this

const options_list = ['Exploring', 'Creating']; // an arraylist holding different activities for the bot to switch between. bot.on('ready', () => { setInterval(() => { const randomIndex = Math.floor(Math.random() * ( ...

Having trouble with Fancybox loading images from an external URL?

Here is an example of functioning HTML code: <a class="fancybox-gallery" href="http://sale.coupsoft.com/uploads/938218/logo.png"> <img class="animate scale animated" src="http://sale.coupsoft.com/uploads/938218/logo.png" alt="Image1"> ...

JavaScript has a flaw in its date validation that allows for incorrect dates like 'dd.mm.0302' or '27.08.0974' to pass through

I have encountered an issue with date validation from the database where some years in the date fields appear to be incorrect (such as 28.02.0302). I need to validate these dates properly, but the functions I found online are not working as expected. How ...

Ways to transfer a function as attributes from one functional element to another?

I've encountered an issue when passing a function as a prop from one functional component (Dashboard) to another (Event). Every time I click the button on the child component that holds the passed function prop in the onClick value, it results in an e ...

How can I notify a particular user using Node.js?

This is the code I have for my server in the server.js file: var socket = require( 'socket.io' ); var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = sock ...

Reading cached JSON value in a Node.js application

Recently, I embarked on creating a node.js application and reached a stage where I needed to retrieve a value from an updated JSON file. However, my attempts using the 'sleep' module to introduce a small delay were unsuccessful. I'm relativ ...

Optimizing the performance of "document.createElement"

When attempting to display multiple rows of data in a popup using a for loop, I initially utilized text strings to create and append the div elements. However, I discovered that using document.createElement resulted in a 20% improvement in performance. D ...

Adjust the ZIndex on a div through interactive clicking

For my new project, I'm exploring a concept inspired by Windows 7. The idea is that when you double click on an icon, a window will open. If you keep double clicking on the same icon, multiple windows should appear. The challenge I'm facing is im ...

What is the process for performing pattern matching on an array in Scala?

As a novice Scala developer, I have a question about working with Scala Array pattern matching: def countErased(sorted: Array[Array[Int]], acc: Int): Int = { sorted match{ case Array() | Array(_) => acc case Array(h,n,_*) => ...

Transferring information between postponed functions

Currently, I am incorporating deferred functions with .done and facing a situation like this: askTime(number).done(formatTime).done(function(html){ times += html; }); Despite the fact that formatTime returns data, the html variable contains the data r ...

Accessing Child HTML Elements with VueJS2

When working with Vue, I usually use the ref keyword to access components. However, I am struggling to understand how to access HTML tags from within a component. I attempted: <input type="text" ref="searchAddress" id="searchAddress" name="searchAddre ...

Is there a way to determine if an app is installed on a phone using Javascript within Safari on iOS 9 or later?

Prior to iOS 9, one method of determining whether an app was installed on an iPhone using javascript involved utilizing a custom URI scheme followed by a timeout: window.location = "yourapp://"; setTimeout(function() { window.location = "h ...