Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript?

for (let key in dict) {
  if (obj.hasOwnProperty(key)) {
    obj[key] = dict[key];
  }
}

If obj is a TypeScript object (an instance of a class), is there a method to achieve the same operation?

Answer №1

Is there a way to perform the same operation if obj is an instance of a TypeScript object (class)?

Your JavaScript code can be used in TypeScript since it is valid (learn more). Here's an example:

class Foo{
    foo = 123
}

const dict = new Foo();
const obj = {} as Foo;

for (let key in dict) {
  if (obj.hasOwnProperty(key)) {
    obj[key] = dict[key];
  }
}

Please note that using Object.keys(obj).forEach(k=> is recommended even for JavaScript, but that is not the main focus of your question here.

Answer №2

Exciting news in the world of ECMAScript 2022:

Check out the newly introduced Object.hasOwn method.

For more details, refer to the ECMAScript 2022 language specification, 13th edition, released in June 2022

Answer №3

The fp-ts library's `has` function proved to be the most effective solution for my specific scenario:

const role = 'mother' as string
const rolesConst = {
  mother: 'mother',
  father: 'father'
} as const
if (has(role, rolesConst)) {
  // role's type is 'mother' | 'father'
}

Answer №4

To achieve this, consider using the ECMAScript 6 feature Object.assign(obj, dict);.

If you are working with TypeScript, keep in mind that the spread operator is more suitable for creating new objects rather than overwriting properties within an existing class.

Remember, when using Object.assign, it only creates a shallow copy and may trigger any setters present in the target class.

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

Intersection observer automatically removes images from carousel (Siema) after they have been viewed

Check out this example to see the issue I'm facing. I've implemented an intersection observer for lazy loading images, here's the code: const pictures = document.querySelectorAll("[data-src]"); function loadPicture(pic){ const src = p ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

How to reveal hidden Div element at a specific index with Angular Material table

In my mat-table, there are several functionalities available: 1. The ability to add or remove rows 2. Adding data into a row using different controls such as combo-boxes, text boxes, etc. One of the controls is a text box labeled "Additional Information ...

I am looking to implement a straightforward drag-and-drop feature using jQuery

Is it possible to drag and select 4 buttons in a browser, similar to how you would do on Windows, using jQuery locally? ...

Is it possible to add a computed value to the bar's end in Chart.JS?

I'm creating a bar graph that has two bars representing different weeks. Currently, it looks like this: https://i.stack.imgur.com/6Avni.png However, I want it to look like this: https://i.stack.imgur.com/TAVqe.png In order to achieve the desired r ...

Tips for handling CSS loading delays with icons in OpenLayers markers

When using openlayers (v4.6.4) with font-awesome as marker icons, the icons do not display upon first load (even after clearing cache and hard reload). Instead, I see a rectangle resembling a broken character. It is only on the second load that they appear ...

Transforming precise military time using Angular and Javascript filtering

There are a few times where I find myself liking 01:45 //and 15:00 I believe this time format is HH:MM in military time? While I have come across some advanced functions that can parse sentences and even include seconds like HH:MM:SS, I am looking for a ...

Create a new division directly underneath the bootstrap column

Imagine having a bootstrap table like this: https://i.sstatic.net/kXHiP.jpg Now, if you want to click on a column and open a div with more details below it, is it achievable with CSS or JavaScript? https://i.sstatic.net/HIfkK.jpg I tried using the Metr ...

Steps to create a toggle feature for the FAQ accordion

I am currently working on creating an interactive FAQ accordion with specific features in mind: 1- Only one question and answer visible at a time (I have achieved this) 2- When toggling the open question, it should close automatically (having trouble with ...

The error notification is not appearing in the correct location

I've been troubleshooting my jQuery error function for hours now (including the success function). I'm struggling to figure out how to display an error message only below the button that I click. To help clarify my issue, I've created a JSFi ...

Transform the Hue or Color of a PNG using ASP.Net, VB.Net, and jQuery

I am currently developing a web page that can combine multiple PNG images into one flat image for users to download. I am looking to incorporate a feature that allows for hue or color adjustments, similar to the color balance functionality in Photoshop. ...

How to effectively utilize `MutationObserver` for monitoring the properties of an `HTMLElement` instead of focusing on its attributes

By using the MutationObserver.observe() method, I am able to monitor changes in a specific attribute. For instance, if I have a Div element and the attribute value is modified, then the designated callback function will be executed. However, if the propert ...

Activate the jQuery UI datepicker with a trigger

Within my code, I have a span element that displays a date in the format mm/dd/yyyy. <span class="editableDateTxt">06/10/2014</span> My goal is to have an inline editable date popup or utilize jQuery UI's datepicker when this span elemen ...

Flipping and rotating images using the power of HTML5 Canvas

Hello, I need assistance with my Electron app that arranges images for batch printing on an industrial printer. The issue I am facing is with images flipping or being mirrored unpredictably. Below is the code snippet responsible for determining whether an ...

Tips for recalling the display and concealment of a div element using cookies

My HTML code looks like this: <div id='mainleft-content'>content is visible</div> <div id="expand-hidden">Button Expand +</div> To show/hide the divs, I am using JQuery as shown below: $(document).ready(function () { ...

How to use a string condition to filter a list of objects in Javascript?

Below is the structure of the object: var objList = [ { "age": 19, "valueField": 34, "booleanField": false }, { "age": 15, "valueField": 5, "booleanField": false }, { "age": 22, "valueField": 17, "booleanField": true } ]; Given the condition ...

Asynchronous Function Implementation of Cookies in JavaScript

Here's my query: Is it possible to store a cookie within an async function? For example, creating a cookie from this fetch and then accessing it later within the same function while the fetch continues to update the value each time the function is ex ...

Ways to enhance the efficiency of this javascript duplicates

I recently wrote this JavaScript code but, as I am still in the early stages of learning, I am struggling to optimize it efficiently. I ended up duplicating the code for each if statement. $(function() { var lang = $(".lang input[type='checkbox&a ...

Authenticating the Gmail API using a specified user ID

Is there a way to manually input email and password for authentication in the Gmail API without using the default Google popup? I need users to enter their login credentials directly, but I can't figure out how to do it. The code I am currently using ...

Tips for displaying subtotal in a Vue application using Firebase Realtime Database

I am currently troubleshooting a method in my Vue app that is designed to calculate the total value of all items sold. Despite seeing the correct values in both the database and console log, the calculation seems to be incorrect. Could there be an issue wi ...