What is the best way to merge two arrays, preserving all keys and values without any overwriting?

Trying to explain this might be a bit tricky, but hopefully I am able to convey my message clearly. Let's say you have an array structured like this:

  mainArray: [
    {
      name: '',
      age: null,
      gender: null,
      hobbies: []
    }
  ],

Now, you want to update this array by adding the values from another array (without replacing any existing keys), which looks like this:

const newArrayToAddToMainArray = [{
     age: 25,
     name: "Alice"
     gender: "female"
    },
    {
     age: 30
     name: "Bob"
     gender: "male"
    }]

So that your mainArray ends up looking like:

const mainArray = [{
     age: 25
     name: "Alice"
     gender: "female"
     hobbies: []
    },
    {
     age: 30
     name: "Bob"
     gender: "male"
     hobbies: [],
    }]

Is there a way to accomplish this task?

Answer №1

In order to expand the array, you can follow the method outlined in JavaScript equivalent of jQuery's extend method

For a clear example, refer to this link https://jsfiddle.net/06mwgqsf/

var existingArray = [{
  name: '',
  age: null,
  gender: null,
  preferences: []
}];

var newArrayToBeAdded = [{
    age: 1,
    name: "Alice",
    gender: "female"
  },
  {
    age: 2,
    name: "Bob",
    gender: "male"
  }
];

function addToArray() {
  for (var i = 1; i < arguments.length; i++)
    for (var key in arguments[i])
      if (arguments[i].hasOwnProperty(key))
        arguments[0][key] = arguments[i][key];
  return arguments[0];
}

var template = existingArray[0];
var temporaryArray = [];

for (var x = 0; x < newArrayToBeAdded.length; x++) {
  var tempObject = addToArray({}, template, newArrayToBeAdded[x]);
  temporaryArray.push(tempObject);
}

existingArray = temporaryArray;

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

Potential 'undefined' object detected in Vuex mutation using TypeScript

Currently, I am diving into learning Vue.js alongside Vuex and TypeScript. While working on my application, I encountered an error stating "Object is possibly 'undefined'" within the Vuex Store. The error specifically arises in the "newCard" mut ...

Looking to add custom Google fonts to your NextJS 13 project? Running into issues with link tags not working as

Attempting to utilize Google Fonts on a project built with Next.js, specifically the latest version 13, but encountering issues with importing Google Fonts like Poppins correctly. In the past, simply adding link tags to either the _document.js or _app.js ...

Creating dynamic bar chart visuals using Morris.js with JSON responses

Utilizing the morris.js library, I am extracting and plotting bar charts from data retrieved through a webservice. Issue: The format of my webservice URL is as follows: http://localhost:9999/hellowebservice/search?select=* I populate the select query ...

Troubleshooting: Discord bot failing to initialize on Heroku

After successfully hosting my bot on Heroku for a while, I temporarily switched back to self-hosting to update to discord.js v13. Now that I'm done with the updates and trying to re-host the bot on Heroku, I'm encountering this error: (node:4) Un ...

JavaScript code not functioning on WordPress website (no impact)

I've encountered a strange problem. Here is the code snippet: (function($){ $("#maps1").hover( function(){$("#kontakt_os_1").hide();} ); $("#maps2").hover( function(){$("#kontakt_os_2").hide();} ); $("#maps3").hover( ...

When attempting to import Three.js canvas on Github Pages, a 404 error is received

While attempting to host my webpage with a three.js background, I encountered an issue where everything loads properly when hosted locally, but nothing loads when pushed to GitHub pages - only the HTML is visible. I am utilizing Vite to package my code an ...

Access the state of a Vuex module within a different module's action

I'm feeling a bit lost when it comes to working with Vuex store components. How can I access the state of another module? I've tried various methods to retrieve data from the store, but I always end up with an Observer object. What is the corre ...

At what point is a $.cache considered oversized?

After coming across a fascinating tutorial, I learned that certain memory leaks in jQuery can be identified by monitoring the size of the $.cache variable. It was emphasized to always keep an eye on its size, as it could indicate potential issues if it bec ...

Failed to execute test suite in React and Jest framework

While working on updates for our existing project, I encountered an error that is causing some of the tests to fail: FAIL src/components/changelog/__test__/ChangeLogOverView.test.tsx ● Test suite failed to run TypeError: Cannot create property & ...

Jest tutorial: mocking constructor in a sub third-party attribute

Our express application uses a third-party module called winston for logging purposes. const express = require('express'); const app = express(); const { createLogger, transports } = require('winston'); const port = process.env.PORT | ...

What is the best method to eliminate whitespace from array values using JavaScript and jQuery?

When I extract a number value from an array and append it to the DOM, there is an unwanted blank space before the value that needs to be removed. The desired result should look like this. data-filter-class="["4"]" for (var i=0, len=str ...

Compel the browser to launch a fresh tab

I'm currently working on an app that involves uploading files. One issue I'm facing is that the file system pop up doesn't close after the upload, causing a quarter of the screen to be covered while the test keeps running in the background. ...

How to implement an external font in AngularJs

I am developing a multilingual website with AngularJS and need to load a font using a .woff file. However, I only want to load the font when it corresponds to the specific language being used on the site. function init(lang){ if(lang == 'eng') ...

What is the best method for eliminating buttons and text in a row using CSS?

I faced an issue when trying to create a row, so I improvised with the following setup. However, I actually need a proper row layout for both the Google button and telephone number button. Here are my CSS snippets: .google-button { color: white; borde ...

Retrieve all the values from a form with identical names using angularjs

I have a form with two text boxes, one for entering a name and the other for an email. There is also a button to add a new row with these two text boxes. I am attempting to retrieve the values of Name and Email using AngularJS, but I am new to Angular. Be ...

Ensuring the proper sequence of operations within a jQuery ajax callback function

I am facing an issue with my jQuery ajax function. The callback function includes two actions: 1) Taking the ajax result (which is an html form) and inserting it as the inner html of an html span. 2) Submitting this form How can I make sure that the form ...

Sorting Multidimensional Arrays in PHP

I am struggling to organize this complex array based on the [sort_order] attribute. Despite my extensive research, I have not been able to find a solution. Could someone please offer me some assistance? The goal is to rearrange the array in the followin ...

angucomplete-alto automatically fills in data based on another input

Having two autocomplete select boxes with a unique feature has been quite interesting. The first input accepts a code that is related to a label, autofilling the second input with the corresponding object once the code is selected in the first input. Howev ...

Barba.js (Pjax.js) and the power of replacing the <head> tag

I have been using barba.js to smoothly transition between pages without having to reload the entire site. If you want to see an example, take a look here. Here is a snippet of code from the example: document.addEventListener("DOMContentLoaded", func ...

MixedUp Order in JSON

Whenever my application generates a JSON file, the updated content causes the order of elements to be mixed up. This leads to unnecessary differences showing in the diff even when the actual changes are minimal. Is there any way to maintain the original or ...