Combine two arrays found within an object by eliminating a specific property of the object

In my possession are two elements a and b, both housing arrays. My goal is to combine the arrays contained in each element and create a new composite element that includes both the arrays and text nodes.

Here is my code snippet:

  var a = {
            name1:[1,2],
            name2:[3],
            name3:'alisha',
            name4:'japan'
          };

   var b = {
            name1:[4],
            name2:[5,6],
            name3:'hello alisha!!'
          };


 newobject = function (obj1, obj2) {
       var obj3 = {};
       for (var attrname in obj1) {
         obj3[attrname] = obj1[attrname];
       }
       for (var attrname in obj2) {
         obj3[attrname] = obj2[attrname];
       }
        return obj3;
 };

 console.log(newobject(a,b))

Purpose of the above code:

I have two objects a & b which may contain varying as well as similar data. The intention is to merge the array data if both objects share the same property. For string properties, I wish to update them with matching properties from object **b**.

The provided output may not be precise but it serves as a valuable hint towards the solution

Desired Output:

  {
        name1:[1,2,4],
        name2:[3,5,6],
        name3:'hello alisha!',
        name4:'japan'
  }

Please refrain from utilizing jQuery

Answer №1

If you are looking to merge the exact example shown above, here is the code that will help you achieve that.

It may be important to note in your situation how you handle scenarios where a.name1 is a string while b.name1 is an array, and so on.

var x = {
  name1: [7, 8],
  name2: [9],
  name3: 'emma',
  name4: 'france'
};
var y = {
  name1: [10],
  name2: [11, 12],
  name3: 'hi emma!!'
};

function combine(x, y) {
  var z = {};
  
  for (var key in x) {
    z[key] = x[key];
  }
  
  for (var key in y) {
    z[key] = (Array.isArray(x[key])) ? x[key].concat(y[key]) : y[key];
  }
  
  return z;
}

console.log(combine(x, y));

Answer №2

To easily expand the functionality for checking other data types such as object, you can modify the code below:

var x = {
  key1:[7,8],
  key2:[9],
  key3:'john',
  key4:'korea'
};

var y = {
  key1:[10],
  key2:[11,12],
  key3:'hello john!!',
  key5:'new key'
};

function combine(x, y) {
  var z = Object.keys(x).reduce(function(result, keyValue) {
    if(!(keyValue in y)) {
      result[keyValue] = x[keyValue]
    } else if(Array.isArray(x[keyValue]) && Array.isArray(y[keyValue])) {
      result[keyValue] = x[keyValue].concat(y[keyValue])
    } else {
      result[keyValue] = y[keyValue]
    }
    return result
  }, {})

  z = Object.keys(y).reduce(function(result, keyValue) {
    if(!(keyValue in result)) {
      result[keyValue] = y[keyValue]
    }
    return result
  }, z)
  return z
}

var z = combine(x, y)

Answer №3

let objectOne = {
     type: [10, 20],
     color: [30],
     name: 'John',
     country: 'USA'
    };
let objectTwo = {
     type: [40],
     color: [50, 60],
     name: 'Hello John!!'
    };

function combineObjects(obj1, obj2) {
  for (let property in obj2) {
 obj1[property] = (Array.isArray(obj1[property])) ? obj1[property].concat(obj2[property]) : obj2[property];
  }
 return obj1;
   }

console.log(combineObjects(objectOne, objectTwo));

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

Is there a way to fix the error "The requested resource does not have the 'Access-Control-Allow-Origin' header" within Express using Firebase functions?

Trying to send an email through nodemailer using Firebase functions, but encountering errors. The data for the email will come from a form. Error message: Access to XMLHttpRequest at 'my-firebase-functions' from origin 'my-angular-web-app&a ...

Text in jQuery is only centered on lines that come after the first line

Looking to create a quiz where clicking the Begin button triggers a jQuery animation, displaying text. The challenge arises when the centered text shifts alignment if it spans multiple lines during the animation. The issue is ensuring that even single-lin ...

Check to see if the event handler is triggered and the promises are executed in sequence (syncronously)

I have a Vue button click handler that, depending on the arguments it receives, can do the following: execute request A only execute request B only execute request A and then request B sequentially (request B is only called if request A completes successf ...

Errors related to missing RxJS operators are occurring in the browser, but are not showing up in Visual Studio

Recently, I encountered a peculiar problem with my Angular4 project, which is managed under Angular-CLI and utilizes the RxJS library. Upon updating the RxJS library to version 5.5.2, the project started experiencing issues with Observable operators. The s ...

Lock the initial column in an HTML table

Hey there! I've been trying to freeze the first column of my HTML table, and while I managed to do so after a few attempts, I encountered an issue. When I scroll the table horizontally, the columns on the left seem to overlap with the first column, an ...

Can someone show me how to toggle <td> elements, also known as 'table data cells', in Javascript?

My goal is to create a functionality where I can click to show/hide table data cells. Despite trying various methods to toggle their display, I have hit a roadblock in my progress. No matter how many functions I attempt, I keep encountering the same error ...

What methods can be used to manage keyup events?

After following a tutorial for my class project on creating a 'frogger-like' game, I encountered a challenge with implementing player movement using arrow keys. The event listener provided in the tutorial facilitated this movement: document.addE ...

What is the correct way to invoke a function within a JSX exported function?

Below is a snippet of code from my home.js file in a React App: function pin(){ var url = "http:myurl" axios.get(url) .then((res)=>{ if(res.data){ var txt = JSON.stringify(res.data) var lat = res.latitude var lng = ...

Leverage array mapping functionality to generate React components within a separate component

Currently, I am retrieving data from an API and storing the results in an array. The issue arises when trying to map the array to a child component since it is initially empty. How can I ensure that the array mapping only executes when there is data in the ...

Switching up the image using a dropdown selection menu

I am struggling with updating an image based on the selection made in a dropdown menu. I am quite new to javascript, so I believe there might be a simple issue that I am overlooking. Here is my attempt at doing this: JS: <script type="text/javascript" ...

Tips for updating data-ng-init with a directive

Is there a way to automatically refresh the variable assigned in data-ng-init whenever the source data changes, without having to do it through the controller? I'm looking for a directive that can achieve this. Any suggestions or examples would be ap ...

An issue has been detected in the constants.json file located in the constants-browserify

I organized my folders into client-side and server-side categories, but I failed to work from a parent folder perspective. Now, as I attempt to deploy to Heroku, I realize that I need one main folder for the deployment process. To address this issue, I dec ...

Design a unique UIButton that can be customized to display various data points

I am facing a challenge with displaying an array of content. The issue is that creating a button for each item in the array is not practical, especially if the array has many items. I am seeking help to come up with a solution to generate a single button t ...

Responsive images in CSS3/HTML5 are designed to adapt to different

I am looking to implement responsive image sizing based on the webpage size. My images come in two different sizes: <img src="images/img1.jpg" data-big="images/img1.jpg" data-small="images/img1small.jpg" alt=""></img> The data-small image has ...

Generating visual content from an application programming interface

<div class="row box"> <div class="col-md-4 pic"></div> <div id="temperature" class="col-md-4 change make_blue bigger_text"> Placeholder </div> <div class="col-md-4"> <button id="getChange" class="make_ ...

Symfony2 compresses CSS and JS files to improve performance

Currently, I am attempting to execute php app/console assetic:dump in order to test my production environment. While my css file gets generated successfully, the js file does not. The following error message is displayed : C:\wamp\www\p ...

VueJS does not show a component if it is contained within a v-if or v-show directive

My goal is to show a component when the 'Add Patient' button is clicked using a v-if directive: // within <template></template> <button type="button" class="btn btn-info" @click="showPatientForm">Ad ...

Building a Dynamic Web Widget with the Perfect Blend of HTML, JS,

While developing a javascript-based web widget, I am aiming to steer clear of using iframes and avoid relying on the page's CSS. It is infeasible for me to utilize custom CSS, as it defeats the purpose, and iframe integration would not present a user- ...

Encountering an issue with the npm start command in my React application

After using npx create-react-app basic to create a React app, I navigated to the basic folder and attempted to start it with npm start. However, I encountered the following error: npm start <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Utilizing an undefined constant in angular programming may lead to unexpected errors

Seeking assistance in generating random first and last names based on gender for a form using Angular. I am relatively new to Angular and keep encountering this error whenever the Use of undefined constant firstName - assumed 'firstName' Here ...