Swapping out a unique item found in two different arrays

Having 2 arrays:

var alleditvals= {username: "twooooo", password: "two_p", address: "two_add"};
var a= {username: "two", password: "two_p", address: "two_add"};

My goal is to replace only the difference ("twoooo") into the object a, making it similar to alleditvals.

In my code, a comes from an array named add_data, hence I utilize the map function:

add_data.map((a,i)=>
  i===count_edit ? alleditvals : a
)

where count_edit gets updated as a number. By checking if the index of add_data corresponds to count_edit, I include the value of alleditvals, otherwise retain the value in add_data (which is a). The challenge with this approach is that it replaces every object inside add_data when the condition holds true, including fields like password and address. Could you please suggest a method where I can selectively replace only the item that has changed?

Appreciate your help.

Answer №1

It seems like your intention is not to have variable a equal alleditvals entirely. As Kraylog pointed out, this would result in losing any properties unique to a that are not in alleditvals.

A better approach would be to iterate through the properties of the object and only copy over the fields that meet certain conditions. For example:

for (x in alleditvals) {
    if (x === “username”) {
        a[x] = alleditvals[x];
    }
    // add more conditions as needed
}

If you truly want to overwrite the differences and keep the properties of a that are not present in alleditvals, you can try something like this:

for (x in alleditvals) {
    if (
        a.hasOwnProperty(x) // only update if a already has the key from alleditvals
        && a[x] !== alleditvals[x]
        ) {
        a[x] = alleditvals[x];
    }
}

Answer №2

Implement the use of Object.assign.

var initialVals = {name: "John", age: 25, city: "New York"};
var changes = {age: 30, city: "Chicago"};

initialVals = Object.assign(initialVals, changes);

Answer №3

Understanding your query, the following solution may align with your requirements:

var alleditvals= {username: "twooooo", password: "two_p", address: "two_add"};

var a= {username: "two", password: "two_p", address: "two_add"};
var b= {username: "three", password: "two_p", address: "two_add"};
var c= {username: "four", password: "two_p", address: "two_add"};

let add_data=[a,b,c];

for (let x in add_data) {
   if(add_data[x].username!==alleditvals.username){
     add_data[x].username=alleditvals.username
   }
   /* other fields is same:
   if(add_data[x].password!==alleditvals.password){
     add_data[x].password=alleditvals.password
   }
   */
}

console.log(add_data)

Feel free to modify and execute this code snippet on this link.

Answer №4

To effortlessly achieve this using modern javascript, simply utilize the spread operator:

newObject = { ...originalObject, ...newValues }

After this operation, newObject will contain all the properties of the original object along with any new ones from newValues that were not present in the original object.

If your goal is to combine both the new values from newValues and replace any existing properties in the original object with the corresponding ones from newValues, essentially merging over the original object, then you can simply reverse the order:

newObject = { ...originalObject, ...newValues }

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 it preferred to utilize v-show in combination with v-for?

I understand that using "v-if" with "v-for" is discouraged, but I'm unsure about the case of "v-show" since it simply toggles the display attribute. Here is the code for reference. Essentially, I am trying to switch between 3 different types of fi ...

A custom Mongoose schema attribute configured with distinct values

I've been working on some code and here is what I have: var userSchema = new mongoose.Schema({ email: String, password: String, role: Something }); I'm aiming to set specific values ('admin', 'member', 'guest&apos ...

The leaflet popup fails to open for the second time

I used a for loop to create markers on the map. When I click on a marker, a popup opens. However, after clicking on the same marker a second time, the popup does not open. My $scope.resSearchAnnouncement contains JSON data. How can I resolve this issue? ...

Switching the navbar image with HTML and JavaScript when clicked

Looking to change the image upon clicking on any of the navbar items. Emulating the navigation bar behavior from this website : This is my current progress : The HTML file : <html lang="en"> <head> <meta charset="utf-8" /> ...

In Django, the Ajax function will fail to execute if any of the required input fields are left empty

I'm currently using an AJAX function that works well when values are entered for all three fields: pname, psection, and rinput-json. However, it fails to work if any of these fields are left empty. <script type="text/javascript"> funct ...

Discovering if a Powershell array includes some elements of another array

Having 2 Arrays $Array1 = Get-Disabledusers SIDS $Array2 = %Unnecessarytext(SIDS).VHDX Attempting to compare Array1 and Array2 and show only the elements in Array2 that include Array1. The challenge is, the comparison returns not equal due to lack of exa ...

Tips for duplicating a 2D array in Python

X represents a 2D array. I am looking to create a new variable Y that holds the same values as array X, without any subsequent changes to Y affecting X. It may seem logical to use y = x, but this does not work with arrays. If I follow this approach and ma ...

Ways to incorporate react suspense with redux toolkit

I am currently using Redux toolkit to display data from an API, and I want to show the user a "loading data..." message or a spinner before displaying the city information. I have been attempting to use React Suspense, but it doesn't seem to be worki ...

The issue with the jQuery function lies in its inability to properly retrieve and return values

Within my code, I have a function that looks like this: $.fn.validate.checkValidationName = function(id) { $.post("PHP/submitButtonName.php", {checkValidation: id}, function(data) { if(data.returnValue === true) { name = true; } else { ...

Having trouble initialising an array of objects in TypeScript? (TS1109: Expression expected)

While working on my project, I encountered a problem when trying to create an array of objects: Error TS1110: Type expected Error TS1109: Expression expected https://i.sstatic.net/Y5qb8.png This is how my array is structured: export let COUNTRIES: A ...

Discover the ins and outs of the "DOM" within a string, treating it as HTML in AngularJS

Looking to extract data from a legal HTML string based on tags and attributes, but want to avoid using jQuery in favor of Angular. Are there built-in functions in Angular for this task? ...

Unable to trigger onActivated in Quasar (Vue 3) component

I can't seem to get the onActivated function in Vue 3 to trigger, even though I've implemented it before successfully. It's puzzling me as nothing seems to be happening. Currently, I'm using Vue version 3.0.0. Here is a snippet of my co ...

Is it possible to apply CSS based on a component's displayName?

Are you a CSS pro? I'm attempting to apply a class that will make all descendants of an element read-only, but for some reason the style isn't being applied as expected: #ComponentDisplayName * { -webkit-user-select: text; -moz-user-sel ...

Issues with Markdown text editor code, table, and list functionalities are causing malfunction

Looking for a solution to use markdown editor for writing blog posts? If you're facing issues with code blocks, list items, tables, etc., not working correctly after publishing your markdown-based posts, while other elements like images, links, and bo ...

Guide to Implementing the GitHub Fetch API Polyfill

I'm facing an issue with making my code compatible with Safari by using the GitHub Fetch Polyfill for fetch(). I followed the documentation and installed it using: $ npm install whatwg-fetch --save Although I completed this step, I am unsure of how ...

Numerous buttons activating a single modal component

I have an array called videos, which contains objects of the type Video (defined below). My goal is to create a functionality where clicking on a specific video button opens a modal containing information about that particular video. interface VideosInfo ...

Whenever I click on a button, I want to modify the background color of my react-modal

Having an array of images with clickable overlays and a modal that changes the background color based on the overlay name when clicked is the goal. However, passing this value as a prop proves challenging since the images are generated through a function a ...

Discover identical JSON elements in 2 JSON arrays using JavaScript and add CSS styles to the corresponding items within a UL list

In order to manipulate JSON data using JavaScript, I am required to create an HTML UL list of tags based on a JSON array of Tag items. Furthermore, there is a second set of Tags in another JSON data-set that needs to be compared with the first Tag JSON da ...

AngularJS integration with Google OAuth

I'm working on integrating Google OAuth in AngularJS. Below is the code snippet for creating a Google sign-in button and the corresponding callback function. // Function for initializing Google sign-in <script type="text/javascript> a = f ...

Want to display a button depending on the page you are navigating from in Ionic?

My home page displays a list of items, and whenever I add a new item, I want it to return to the home page. However, if I navigate back to the root from the addItemPage, I also want to display a button for saving the list and making an HTTP call. I'm ...