Combining objects by their values while retaining distinctive values within an array

I've been struggling to find a clean solution for merging two objects like the example below:

obj1 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE1"
}

obj2 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE2"
}

//I want to merge them to achieve the following output

obj3 = {
  key1: "ABC",
  key2: "123",
  key3: ["UNIQUE1", "UNIQUE2"]
}

I am looking for a way to keep unique values per key in an array. I have explored options like lodash but haven't found a suitable solution yet. Any guidance would be greatly appreciated!

Answer №1

To merge two objects and handle conflicts based on a condition, you can utilize the reduce function along with looping through the keys of obj1.

var obj1 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE1",
  key5: "4567",
  key7: "y",
  key8: "8y",
  key9: "yi89",
  key0: "dhdh64",
  key12: "dhdh64",
  key11: "dhdh64"
}

var obj2 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE2",
  key4: "1212",
  key6: "a",
  key7: "z",
  key11: "z"
}

var result = Object.keys(obj1).reduce((a, k) => {
  a[k] = obj2[k] === undefined || obj1[k] === obj2[k] ? obj1[k] : [obj1[k], obj2[k]];
  return a;
}, { ...obj1, ...obj2 });

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

Resource

Answer №2

To create a new object, you can utilize the mergeWith method and provide an empty object as the first parameter. Then, by comparing the values of two properties, you can generate an array based on the comparison result.

const obj1 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE1"
}

const obj2 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE2"
}

const result = _.mergeWith({}, obj1, obj2, function(a, b) {
  if (a === undefined) return b
  if (a != b) return [].concat(a, b)
})

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

Answer №3

To iterate through an object's key, you can use the for...in loop to compare whether the values are equal or not. Here is a sample code snippet:

var obj1 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE1"
}

var obj2 = {
  key1: "ABC",
  key2: "123",
  key3: "UNIQUE2"
}
var result={};
for(var property in obj1){
  if(obj1[property] == obj2[property]){
    result[property] = obj1[property];
  }
  else{
    var tempArray = []; 
    tempArray.push(obj1[property]); 
    tempArray.push(obj2[property]);
    result[property] = tempArray;
  }
}

console.log(result)

Answer №4

When considering that specific scenario

result = {}

for(key in object1){
  result[key] = (object2[key] != object1[key])? [object1[key], object2[key]] :  object1[key]
}

Answer №5

Using the Object.keys method on obj1, we can compare its key-value pairs with those of obj2 and create a new object containing either the matching values or an array of both values. This reduces the need for manual comparison and increases efficiency in handling object properties.

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

What benefits does invoking the .call() method on Observable functions offer?

I am new to Angular and finding it challenging to comprehend some code I came across in the ng-bootstrap project. You can find the source code here. The section that particularly confuses me is the ngOnInit method: ngOnInit(): void { const inputValue ...

The JScolor Color Picker has a slight misalignment

I am having an issue with the jscolor color picker on my webpage. The rainbow part of it appears offset within the rest of the picker. You can see what it looks like on my site here: (https://ibb.co/9N8dHXs). On my website, I have a large canvas for three ...

What is the best way to add a multiselect option in Django to display detailed information for each selected item

Experience the Description Image I am looking to develop a mini demonstration similar to the image provided. When I click on an item in the left column to select a country, I want the right column to dynamically display all the cities of the chosen countr ...

Retrieving data from a multi-dimensional array filled with xpath values

I am relatively new to PHP and struggling with a particular issue. I have successfully created a multidimensional array from an XML file using XPath. While I can navigate through the array and retrieve most values, I am facing difficulty with a specific se ...

The request to http://localhost:3306/socket.io/?EIO=3&transport=polling&t=NQfLxAy encountered an invalid HTTP response, resulting in net::ERR

I'm currently working on a project to build a real-time chatbox using Node.js. Right now, I am facing an issue where I am unable to display the user's entered name in the console. I would greatly appreciate any help with resolving this problem. ...

The jQuery.ajax function fails to trigger

Just dipping my toes into jQuery, so please be patient with me :-) What I'm attempting to do is validate user input in a form by checking the input against a MySQL database and then setting the color based on true or false. I've successfully ac ...

Issue with setting correct typings in Typescript's tapAsync function

I am interested in connecting multiple ES6 async functions using TypeScript and the tap function. The tap function should return the argument if no value is returned from the tapped function, but return the tapped value if there is a return value. typescr ...

Creating a dynamic link in Vue JS is a cinch!

I currently have the following code snippet: <b-dropdown text="Select Factory" block variant="primary" class="m-2" menu-class="w-100"> <b-dropdown-item @click="selectedFactory='China'"> ...

Removing the existing array of strings from a file in C# ASP.NET

Seeking guidance for a task as a beginner. I am looking to remove the displayed string from an "accepted" button. Upon clicking the "accepted" button, the displayed array is transferred to another file. However, I also need the displayed single line array ...

Tips for incorporating 'and' in the 'on' clause of 'join' in knex.js

I need assistance implementing the following SQL code in knex.js: select c.id,c.parent_id,c.comment,u.username,c.postid from comments as c join post_details as p on (p.id = c.postid and c.postid=15)join users as u on (u.id = c.userid); I attempt ...

I am looking for the best way to sort my JSON data based on user roles before it is transmitted to the front end using Express and MongoDB. Any

I scoured the internet high and low, but to no avail - I couldn't find any framework or code snippet that could assist me in my predicament. Here's what I'm trying to achieve: whenever a response is sent to my front-end, I want to filter th ...

Dynamically generate checkbox options based on dropdown menu selection

I'm currently designing a form that will dynamically display checkboxes within a div based on media files uploaded by a specific usergroup. Essentially, when a user chooses the group name from a dropdown menu, all relevant media files will be listed a ...

Mastering MongoDB update functions in JavaScript

I've encountered some difficulties while using the MongoDB API to update a document. Despite trying various methods, none of them have been successful so far. Strangely enough, inserting and deleting documents work perfectly fine. Let me explain what ...

Meteor: Form a fresh collection using a single attribute from a current collection

In my Meteor app, I have a collection fullList = new Mongo.Collection('fullList');. This collection consists of an array of objects with attributes like Color, Factor, and Tot. My goal is to create a new collection or array that specifically con ...

Error: The fetch API encountered an unexpected termination before completing the request

A new issue has come up in my project, and although I found a similar problem on this link, it does not address my specific issue. What I have set up is a straightforward API using nodejs, express-framework, and mongoose. The issue lies with the fetch API ...

Is there a method in CSS Grids to wrap the implicit grid while employing grid-auto-flow: column?

How can I achieve a layout consisting of two 4x2 grids that flow into each other, instead of being positioned side by side? Essentially, I want to split an 8x2 grid into two halves and stack them vertically. Is there a way to make the layout wrap around it ...

Generate a hyperlink that directs to a page and triggers the expansion of an accordion section

I am currently working with a Bootstrap 5 accordion component: <div class="accordion" id="accordionIndexPage"> <div class="accordion-item"> <h2 class="accordion-header" id="flush-headingOne& ...

Exploring the intricacies of v-bind in the context of v-for loops

Consider the following code snippet: .fav { background:”blue”} <li v-for="(book, index) in books" :key="book.title" :id="this.code + '-' + index" :class="{fav: book.isFav}" > {{book.ti ...

What are some creative ways to reveal a concealed card through animation?

I have a collection of MUI cards where one card remains hidden until the others are expanded. My goal is to add animation to the hidden card so it doesn't abruptly appear. Below is the styling and logic for achieving this: ** Styling ** const useStyl ...

Is it secure to use ES6 in Typescript with nodejs/koa?

As I transition to using TypeScript in a Node.js/koa project, I came across the need to modify the .tsconfig file to target ES6. Otherwise, an error message will appear stating: Generators are only available when targeting ECMAScript 6 or higher. // index ...