Combining objects based on key in Javascript

I am working with an array of objects that have specific properties:

var countries = [
    {id: SWE, value: 5},
    {id: DE, value:10},
    {id: SWE, anotherValue: 11},
    {id: DE, anotherValue: 15}
]

My goal is to merge the array elements based on their id values. The desired output should be:

countries = [
    {id: SWE, value: 5, anotherValue: 11},
    {id: DE, value:10, anotherValue:15}
]

Currently, I am achieving this by using a for loop with many if and else statements.

Question: Is there any (more elegant) built-in JavaScript functionality to simplify this task?

I have attempted to search online for solutions, but as a beginner in JavaScript, I am unsure of what keywords to use. Any assistance would be greatly appreciated.

Answer №1

Give this a shot:

function mergeByIdentities(arr){
  var obj={};
  
  arr.forEach(function(element){
    if(element && element.id){
      obj[element.id] = obj[element.id] || {};    
      for(var key in element) obj[element.id][key] = element[key]
    }
  });       
  
  return Object.keys(obj).map(function (idKey) {return obj[idKey]});
}

var countriesList = [
    {id: 'SWE', value: 5},
    {id: 'DE', value:10},
    {id: 'SWE', anotherValue: 11},
    {id: 'DE', anotherValue: 15}
]
document.write(JSON.stringify(mergeByIdentities(countriesList)))

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

How do I redirect with a GET method after calling the *delete* method in Node / Express server?

As someone new to AJAX and Node, I encountered a dilemma that I hope to get some guidance on. Here's the issue: I have a DELETE ajax call that removes a row from the database and I want to redirect back to the same route with a GET method afterwards. ...

I am having trouble getting event handlers to work with a group of buttons in JavaScript

I'm facing a problem where I'm attempting to add event handlers to buttons stored in an array. Upon clicking a button, it should trigger a function, but for some reason, it's not working and I can't seem to identify the issue. Below is ...

Retrieving PHP data, utilizing the split method to break apart the commas within the string, and then displaying the information within a div using AJAX for a continuous refresh cycle every 3 seconds

I am attempting to extract data from a PHP string like '10,58,72,15,4,723,' and split it by commas into arrays using the split() method. My goal is to then place these arrays into different div elements and update the data every 3 seconds. Below ...

Creating Shapes in Leaflet: A Step-by-Step Guide to Drawing Like a Painter

I am attempting to utilize the plugin https://github.com/tcoupin/leaflet-paintpolygon for image annotation in a multipoint circle shape. Unfortunately, the plugin is not functioning correctly as a result of a bug present in the libraries it relies on. Ar ...

Updating the dynamic site script to be compatible with the newest version of the jQuery library

After finding a script on http://css-tricks.com/dynamic-page-replacing-content/, I decided to edit it to suit my needs. Initially, everything worked perfectly with "jquery-1.4.4". However, when I tried using versions later than "jquery-1.5", the active cla ...

Include the url of the html file in your JavaScript code

I have a piece of code that I want to include in my JavaScript instead of HTML. The code is as follows: <script async src="https://www.googletagmanager.com/gtag/js?id=ID"></script> Since all my functions are written in JavaScript, I ...

My local requests are being blocked by both Chrome and Firefox

Recently, I've been experimenting with local flash development and trying to inject my swf file into a website served by my test server. To enable loading of local resources in Chrome, I set --disable-web-security. In FireFox, I made the following a ...

function to choose in antd datepicker component

Is there a way to obtain the currently selected date within the onSelect function after updating the selected date in the state? onSelect = (cal) => { this.setState({ selectedValue: cal }); alert(this.state.selectedValue); After making ...

Tips for assigning a postgres query to a variable when working with node.js, integrating Discord bot with postgres

My friend and I have been brainstorming a business idea that involves using Discord as our platform. While I am somewhat new to coding, I do have some knowledge in Discord.js, Java, and HTML. Here’s the plan: We will have a website where users can purch ...

Show values in an angular template using an array

I want to showcase values of an array using *ngFor const blockData = [ {text: sampleText1, array: [val1]}, {text: sampleText2, array: [val2, dat2]}, {text: sampleText3, array: [val3, dat3]} ] <div *ngFor="let data of blockData"> ...

Tips for transferring information using '&' on websites

When using jQuery's $.ajax method to send data to add_showcase.php, an issue arises when passing a complex data structure as the "desc" parameter. The data might not be received in its entirety by the PHP file. $.ajax({ type: "GET", ...

Conditional CSS for knockout-style options

I am working with an observable array containing objects question = { ownerUserName: item.id, text: item.text, dataType: item.dataType, personalized: item.personalized, status: item.status, actionUserName: i ...

Issue with Semantic-UI Special PopUp not displaying on screen

I'm currently working on creating a unique pop-up feature using custom HTML, with the intention of adding content to it later on. My console is displaying the following message: Popup: No visible position could be found for the popup. $(document) ...

Identify and add unique keys to duplicate IDs

Have you ever wondered how to identify all duplicate IDs when the page is reloaded? Consider this HTML structure: <input type="radio" id="name" /> <input type="radio" id="name" /> <input type="radio" id="name" /> <input type="radio" ...

What is the best way to trigger a refresh in Next.js React component?

Current Tech Stack Versions Next.js : 14.0.3 React : 18.0.2 // TestClientComponent.tsx "use client"; import { IResident } from "@interface/resident.types"; import { getResidents } from "@models/resident.service"; import { So ...

Positioning Backgrounds with Padding in DIV Elements

I am trying to figure out how to add a check mark next to text in a button with specific styling. I have managed to get the check mark aligned properly using Background:left center, but I also want to add padding and adjust spacing. Is there a way to achie ...

Retrieve the outcome of a mongoose query within a designated function

Seeking help with returning a result from my mongoose find operation. While similar questions have been asked before, this one is unique. Here's an example of my user: let UserSchema = new mongoose.Schema({ variable: {type: mongoose.Schema.Object ...

Invoke the onClick function within a setInterval loop

My onClick function is functioning correctly. However, I want to run it periodically using setInterval after it's been triggered by a click event. Here's my attempt at modifying the code: var clickData; var isClicked=0; function onCl ...

Understanding the Class Syntax in Node.js

I'm having trouble understanding how to retrieve the value from a Node JS Class [Trying to use [Symbol.iterator '']]alert(Hello, ${this.name}!); Is there another way to approach this? class User { name = "Anonymous"; sayHi() { ...

What is the best way to apply lodash's max function to a jQuery array?

I'm having trouble extracting the maximum number of rows from two tables. My variable maxRows ends up being a tbody jQuery element instead of the actual maximum value. I've experimented with both the pluck syntax and the long form, but both metho ...