Duplicate object omitting certain fields

I am faced with the challenge of working with two interfaces:

public interface ObjectOne {
   field1: string;
   field2: string;
   field3: string;
   field4: string;
   field5: string;
   ...
}

public interface ObjectTwo {   
   field2: string;
   field5: string;
   field8: string;
   ...
}

Let's say that ObjectOne has 20 fields and ObjectTwo has 10 fields (all of which are part of ObjectOne).

At the end of an action, I need to copy the fields from ObjectOne to ObjectTwo, but without manually mapping each field like so:

objTwo.field2 = objOne.field2;
objTwo.field5 = objOne.field5;
objTwo.field8 = objOne.field8;
...

I am aware that I can destructure ObjectOne as follows:

const {field2, field5, field8, fieldX, ...} = objOne;

and then assign these fields to objTwo in one go:

objTwo = {field5, field8, fieldX, ...};

However, I was hoping for a more elegant solution, almost like an inverse of a spread operator. Speaking of which, here is an example of using the spread operator:

const objOne = {...objTwo, field1, field3, field4, field6, ...};

Using the spread operator on objTwo would result in it inheriting all the fields from objOne, regardless of their object type declarations.

Answer №1

The spread operator can be utilized to extract values you need from an object, leaving out the ones you don't require, as demonstrated in my sample code below using the key one.

const sourceObject = { one: 'one', two: 'two', three: 'three' }
const { one, ...remaining } = sourceObject

const targetObject = { ...remaining } // or simply targetObject = remaining

Answer №2

Loop through the keys of ObjectTwo and assign corresponding values from ObjectOne to them.

Answer №3

The closest approximation to your requirements can be found in the following code snippet:

first = {
   property1: "value1",
   property2: "value2",
   property3: "value3"
};

second = {   
   property2: "value2x",
   property3: "value3x",
   property4: "value4x"
};

Object.keys(second).forEach(function(key) { 
    if (typeof first[key] !== "undefined") second[key] = first[key];
});

// Updated 'second' object:
// {property1: "value1", property2: "value2", property3: "value3x", property4: "value4x"}

Although not perfect, this code only copies defined values from one object to another.

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

When useEffects are linked in such a way that the first one updates a dependency of the second, it can lead to

Modified code block with console logs integrated from approved solution. I have stripped down a search bar component to its simplest form: import React, { useEffect, useRef, useState } from "react"; import axios from "axios"; const re ...

Step-by-step guide to creating a transition effect when the input changes

I'm looking to add a unique effect to my dropdown menu My goal is to create an effect in which the placeholder moves up and the new value seamlessly takes its place, using JS, jQuery, CSS, and HTML. View before transition View after transition ...

React 17 Form not registering the final digit during onChange event

I am currently experiencing an issue with a form that includes an input field of type "number." When I enter a value, the last number seems to be skipped. For example: If I input 99 into the box, only 9 is saved. Similarly, when typing in 2523, only 252 ...

Javascript variable decrement failure

One of the challenges I am facing is with a button in HTML that is set by AJAX to create a new tr element. I have successfully built a function (code provided below) to add it, but now I want to include a counter to keep track of how many rows I have. The ...

Combining data from multiple API calls in a for loop with AngularJS

I'm working with an API that contains pages from 1 to 10 and my goal is to cycle through these page numbers to make the necessary API calls. app.factory('companies', ['$http', function($http) { var i; for (i = 1; i < 11 ...

Installing different versions of a package in npm can be done by loading multiple versions

I am in the process of setting up a web API and I want to provide support for various versions of the underlying library. In essence, I would like to access it through: where x.y.z represents the version of the library I am utilizing. Using npm for mana ...

Is it feasible to save BoxGeometries or MeshLambertMaterial in an array using Three.js?

var taCubeGeometryArray = new Array(); var taCubeMaterialArray = new Array(); taCubeGeometryArray.push(new THREE.BoxGeometry( .5, .5, .5)); taCubeMaterialArray.push(new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture( "image.png" )})); Could ...

Switching Mouse Hover Effect with a Click: A Quick Guide

I am looking to create a unique effect where the color of an element changes on hover, but the hover effect is disabled while clicking on the element and the clicked element turns red. Once the element is clicked, I want to re-enable the hover effect and a ...

What is the best way to store all rows in a dynamically changing table with AngularJS?

I am facing an issue while trying to dynamically add rows for a variable that is a String array in my database. The problem is that it only saves the last value entered in the row instead of saving all of them in an array. Here is my current view code: &l ...

Pop-up modal from Bootstrap appearing on top of the page header

I'm working on a website layout where the header always stays on top of everything. However, whenever I add a bootstrap modal that pops up, it ends up covering the header with a grey area. I've attempted to adjust the z-index values for both the ...

Is there a way to access the parent element within the javascript function of an asp:CustomValidator?

Is there a way to access the parent element in the asp:CustomValidator JavaScript function in order to verify if the associated checkbox has been selected? For instance: I'm faced with this code: <tr> <th class="gray ...

Bootstrap / Blazor - no action when clicking on an image link

Having issues with adding a simple HTML link around an image in my Bootstrap 4.5 / Blazor app. When I click on the link, nothing happens. How is this possible? I've tried using the <a href"..."><img ...> pattern, as well as NavL ...

JavaScript must be able to detect when the checkbox value is reversed, which is dependent on the user-entered data

Hey there, I come across a situation where users are selecting a checkbox to insert or update a row of data in a MySQL database through SparkJava/ Java. The functionality is working fine except for a minor glitch. The issue arises when the checkbox behav ...

Tips for dynamically adding and removing keys from a JSON object

I am working on a code for a car rental website using jQuery mobile. I need to dynamically add and remove keys from a JSON object with true or false values. The goal is to make a selected car unavailable by changing the "available" key to either true or ...

PHP is capable of showing echo statements from the function, however it does not directly showcase database information

My current challenge involves using AJAX to pass the ID name of a div as a string in a database query. Despite being able to display a basic text echo from my function, I'm unable to retrieve any content related to the database. // head HTML (AJAX) $( ...

After integrating session store into my application, nestjs-sequelize is not synchronizing with any models

I'm currently working on developing a Discord bot along with a website dashboard to complement it. Everything is running smoothly, except for the backend Nestjs API that I am in the process of creating. I decided to use Sequelize as the database for m ...

What are some effective strategies for developing an API that has a prolonged response time?

While working on an API endpoint that requires calling multiple external services/DBs, I want to ensure that my users do not face delays in the process. However, the outcome of this process is crucial for their experience. My initial idea is to enqueue th ...

Assign an appropriate label to this sonarqube input field

Sonarqube flagged an issue with the following line of code: <div class="dropdown-language"> <label>{{'GENERALE.LINGUA' | translate }}</label> <select #langSelect (change)="translate.use(langSe ...

Error encountered: "XPathEvaluator is not defined" when using IEDriverServer and Internet Explorer with Selenium and Java in Microsoft Dynamics CRM

As part of my testing process for a CRM application with Selenium Java, I encountered an issue with a button that opens a new window. When executing the test, a Script Log Error appears in the new window stating, ReferenceError: 'XPathEvaluator&apo ...

Retrieve the output of a function in TypeScript

I'm encountering a challenge with returning a string instead of a function in an object value. Currently, an arrow function is returning an array of objects, and one of them needs to conditionally change a value based on the input value. Here is the ...