I possess a pair of items that require merging together while combining any overlapping key values in their properties

I have a scenario where I need to merge two objects and concatenate strings if they have the same key.

obj1 = {
  name: 'John', 
  address: 'Cairo'
}

obj2 = {
  num : '1', 
  address: 'Egypt'
}

After merging, the resulting object should look like this:

merged = {name: "John", num: "1", address: "Cairo, Egypt"}

When using _.defaults(obj1, obj2) or _.merge(obj1, obj2), there's an issue with the address property as it gets overwritten by the value from obj2. Therefore, I'm looking for a way to merge the two objects while concatenating the address properties from each object.

Answer №1

Give this a try:

    function combineObjects(object1, object2) {
      let mergedObject = {
        ...object1,
        ...object2
      };
      Object.keys(object1).filter(key => object2.hasOwnProperty(key)).forEach((key) => {
        mergedObject[key] = object1[key] + "," + object2[key]
      })
      return mergedObject
    }

    object1 = {
      name: 'john',
      address: 'cairo'
    }

    object2 = {
      num: '1',
      address: 'egypt'
    }

    console.log(combineObjects(object1, object2))

Answer №2

If you want to avoid using lodash, you have the option to create your custom function for the task at hand. Here is a simple way to achieve that:

  • new Set - used to identify all unique keys from both input objects
  • for...of - employed to loop through the unique keys determined earlier

function mergeObjects(obj1, obj2) {
  let merged = {};
  for (const property of [...new Set([...Object.keys(obj1), ...Object.keys(obj2)])]) {
    if(obj1[property]) merged[property] = obj1[property];
    if(obj2[property]) merged[property] = merged[property] ? `${merged[property]}, ${obj2[property]}` : obj2[property];
  }
  return merged;
}

const obj1 = { name: 'john', address: 'cairo' };
const obj2 = { num: '1', address: 'egypt' };

const mergedObj = mergeObjects(obj1, obj2);
console.log(mergedObj);

Answer №3

def combineObjects(objectList):
    newObject = {}

    for obj in objectList:
        keys = obj.keys()
        for key in keys:
            if key in newObject:
                newObject[key] = newObject[key] + "," + obj[key]
            else:
                newObject[key] = obj[key]
                
    return newObject

obj1 = {name: 'Alice', city: 'New York'}
obj2 = {age: 25, city: 'Los Angeles'}

print(combineObjects([obj1, obj2]))

By using this technique, you can easily merge multiple objects!

Answer №4

You have the option to utilize _.mergeWith() for merging values of specific keys into arrays, and then apply _.mapValues() to convert those arrays into strings:

const { mergeWith, mapValues, uniq, join } = _;

const customFunction = (predicate, ...objects) => mapValues(
  // Merging the objects
  mergeWith(
    {}, 
    ...objects, 
    // Handling the keys that need unique merging
    (a = [], b = [], key) => predicate(key) ? a.concat(b) : undefined
  ),
  // Transforming the relevant keys' values into unique strings
  (value, key) => predicate(key) ? uniq(value).join(', ') : value
);

const object1 = { name: 'john', address: 'cairo' };
const object2 = { num : '1', address: 'egypt' };

const result = customFunction(key => key === 'address', object1, object2);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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

Implement a Codeigniter model that utilizes JavaScript to insert an ID

Is there a way to retrieve the productid value in PHP code? function getunitstock(){ var productid = document.getElementById('product').value <?php $prodbyid = $this->pos_model->get_productbyid(+productid+)?> document. ...

links to css and javascript

I am having trouble with what should be a simple task! On my webpage, I have this link: <a class='action' href='javascript:void(0)' OnClick='run()'> run </a> Along with the following CSS: .action { color: # ...

Tips for prioritizing new data input at the top of the list

Hey there, I'm having trouble figuring out how to push new data to the top of a list using vue.js and laravel. I've been trying but haven't had any luck so far. If anyone could lend a hand, I would greatly appreciate it. Below is my Control ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Managing Numerous Dropdown Menus: Techniques and Tips

I'm currently working with MUI to design a navigation menu that contains dropdowns within certain links. However, I've encountered an issue where clicking on any button opens the same dropdown menu. Below is my code snippet: function Header() { ...

Next.js: How to retrieve route parameter within getServerSideProps

I need to retrieve data from my Supabase table using the ID provided in the URL slug, for example localhost:3000/book/1, and then display information about that specific book on a page built with Next.js. Table https://i.stack.imgur.com/t5z7d.png book/[ ...

The main content will be displayed on the sub-routes of the child

I'm feeling uncertain about the routes for children. For example, I have an 'About' route with 'me' as a sub-route: { path: '/about', name: 'About', component: About, children: [ { ...

Is it possible to globally modify the component reference <dropdown-component> name in Angular during runtime in a dynamic manner?

I am currently working on an application that utilizes a component called "dropdown-component" throughout its pages. However, due to specific business requirements, I have been tasked with replacing "dropdown-component" with "custom-dropdown-component". Un ...

What is the proper way to access object properties in EJS?

My server has an express API to retrieve food items and I want to display their names on my ejs index file. In order to fetch the data, I have the following code in my server.js file: app.get('/', async (req, res) => { try { fetch ...

Struggling to make a form submit work with AngularJS and a Bootstrap datetime picker

Struggling to create a post and include name and datetime using a bootstrap datetimepicker. After selecting the datetime and clicking add, nothing happens. However, if I manually type in the field and click add, it submits successfully. Despite reading up ...

Encountering the error message "Unable to connect to this site" while attempting to run Angular 8 using Docker Compose

After successfully running npm start for my angular UI application, I encountered an issue when moving API and UI into docker. Every time I tried to access the site, it displayed "This site can’t be reached". Can someone please assist me in identifying w ...

Manipulate an object in Three.js using the ObjLoader functionality

I'm currently working on manipulating an object loaded using OBJLoader in Three.js. The issue I'm facing is that while it's easy to manipulate the object once, I can't figure out how to do so during the animate loop or anywhere outside ...

What is the process to include an image file in a JSON object using PhoneGap?

Having trouble saving an image in JSON. Managed to access the mobile camera with the provided code: var pictureSource; // source of the picture var destinationType; // sets the format of returned value // Wait for PhoneGap to connect with the device / ...

Create an Array with a dynamic name derived from the values of other variables

In my JavaScript project, I am facing a challenge in naming arrays based on dynamic data such as room numbers and user IDs. As the rooms and users are constantly changing, I need to create multiple arrays accordingly. Although this code is incorrect, it s ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: https://i.sstatic.net/OzE98.png Here is what I have been able to achieve: https://i.sstatic.net/7GxdP.png In the second picture, the divs are shown separately. My goal is to display the incoming data in a ...

The alignment of the 3D STL object is not adjusting properly when zooming in with Three.js

Below is the code snippet used to render a 3D object on the screen: this.col=new Color().set(this.colorname); this.renderer = new WebGLRenderer({alpha:true,canvas:this.myCanvas.nativeElement}); this.renderer.setSize(window.innerWidth/2,window.inne ...

Guide to directing a user through an Ajax call to a particular Controller and action

Here is a custom JavaScript function that updates data when the Update button is clicked. function UpdateData() { var obj = { "testData": $("#hdn_EditdsVal").val(), "feature": $("#hdn_EditdsVal").val() }; $.ajax({ url: ...

Use JavaScript to identify and color the intersecting area of two triangles that overlap on a webpage

I created two triangular divs using HTML and I am utilizing jQuery UI to enable them to be draggable. Now, my goal is to overlap these two triangles and change the color of the overlapping area to a different shade. Here is an example: https://i.sstatic. ...

Tips for validating Enum Strings using the newest version of Joi?

Is there a way to validate Enum String? In the past, I followed this advice from: https://github.com/hapijs/joi/issues/1449 enum UserRole { Admin = 'admin', Staff = 'staff' } const validator = { create: Joi.object().keys({ ...

Encountered an issue while integrating CKEditor 5 into a standalone Angular 17 application: "Error: window is

Having trouble integrating CKEditor with my Angular app (version 17.1.2 and standalone). I followed the guide step by step here. Error: [vite] Internal server error: window is not defined at r (d:/Study/Nam3_HK3/DoAn/bookmanagement/fiction-managemen ...