Selecting an object dynamically to add a new property in JavaScript

I am faced with a scenario where I have two objects and I need to add new properties to them. The challenge is that I want to be able to choose which object to work with first before adding the new properties. Here's the proposed logic :

let customizeObjects = (function() {

    // Define the Two Objects
    let university = {}
    let Person = {}

    let addNewPropTo = (objName, newProp) => {
         return objName[newProp] = null;  // Issue in logic 1
    }
    
    let getProperties = (objName) => {
       return Object.getOwnPropertyNames(objName)
    }

    return {
       addNewPropTo,
       getProperties
    }

})();

customizeObjects.addNewPropTo('Person', 'Age'); // Issue in logic 2
customizeObjects.getProperties(Person) // Expected Output : Person = { Age : null }

Answer №1

When encountering the error message in logic fail 1, it indicates that an attempt is being made to add a property to the string objName, rather than the intended object.
In this case, select one of your objects.

let AddNewPropTo = ( objName , new_objProp ) => {
  if (objName === 'Person') {
    Person[new_objProp] = null
    return Person
  }
  if (objName === 'university') {
    university[new_objProp] = null
    return university
  } 
}

The issue in the second logic fail seems to be a simple oversight as the return value is not saved.

const Person = myFn.AddNewPropTo('Person','Age'); // logic fail 2
const props = myFn.getProps(Person) // Desired Output : Person = { Age : null }
console.log(props)

To make the process more dynamic, consider the following approach:

let university = {}
let Person = {}
const map = {
  'Person': Person,
  'university': university
}

let AddNewPropTo = ( objName , new_objProp ) => {
  let obj = map[objName]
  if (obj) {
    obj[new_objProp] = null
    return obj
  }
  return {}
}

Answer №2

I may not be well-versed in typescript, but I was able to achieve the desired result just like you wanted.

Feel free to take a look at this Fiddle for more information.

Here is the code snippet:

let Person = {}

function AddNewPropTo( objName , new_objProp ) {
     return objName[new_objProp] = 1;  // logic fail 1
}
function getProps  (objName) {
   return Object.getOwnPropertyNames(objName);
}


 AddNewPropTo(Person,'Age'); 
 console.log(getProps(Person)) ; //returns ['Age']

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

Creating unique identifiers using node.js

function createUniqueID(count) { var found = false, characters = 'abcdefghijklmnopqrstuvwxyz1234567890', uniqueString = ''; while(!found) { for(var i = 0; i < count; i++) { uniqueString += ...

Ensuring the child div's height does not overflow beyond the parent div

When dealing with a parent div and a child div, both having different heights, how can I specifically retrieve the height of the portion of the child div that is within the boundaries of the parent div? Using document.getElementById("id").style.height prov ...

An assortment of diverse data types in TypeScript arrays

Considering adding type to my existing API, I have a function that can accept a string, function, or object (utilizing overloading). However, it is also able to accept an array of mixed values. Is there a way to have an Array in TypeScript that consists o ...

Interacting with a form input by triggering the onChange event

I am encountering a problem where I need to be able to select a radio button both onChange via keydown and mouse click. However, I am struggling with accessing both event parameters of the on keydown and on mouse click within the same function. As a result ...

Changing the parent scope from the child component does not automatically reflect changes in an ng-repeat

I am facing an issue with the communication between a child controller and a parent controller. I have a function that adds data to a parent array which is used in an ng-repeat directive. Although the parent array gets updated correctly and its length is ...

Determining the specific condition that failed in a series of condition checks within a TypeScript script

I am currently trying to determine which specific condition has failed in a set of multiple conditions. If one does fail, I want to identify it. What would be the best solution for achieving this? Here is the code snippet that I am using: const multiCondi ...

Public directory assets not accessible

After working extensively with Node and Angular, I realized my back-end structure needed some serious attention. In an effort to streamline my process, I decided to separate the client and server components and create a reusable skeleton for future applica ...

Selecting an option with a specific index in Angular 2 RC2

I have encountered a situation where the select options are non-unique, with the same value representing different things. This is how our data is structured and I need to work within those constraints. <select id="mySelect"> <option value = "1 ...

The autocomplete feature is not displaying the data in the Bootstrap modal, only the list is visible

Having trouble with autocomplete in the bootstrap modal. The search for a book only shows black dots. Any solutions to this issue? As shown in the image, I've attempted to use CSS z-index but the problem persists. https://i.sstatic.net/e1ga9.png publi ...

axios interceptor - delay the request until the cookie API call is completed, and proceed only after that

Struggling to make axios wait for an additional call in the interceptor to finish. Using NuxtJS as a frontend SPA with Laravel 8 API. After trying various approaches for about 4 days, none seem to be effective. TARGET Require axios REQUEST interceptor t ...

Tips for converting NULL% to 0%

When running my calculatePercents() method, I am receiving NULL% instead of 0%. https://i.sstatic.net/NSbls.png Upon checking my console.log, I noticed that the values being printed are shown as NULL. https://i.sstatic.net/A7Jlk.png calculatePercents() ...

Managing Import Structure in Turborepo/Typescript Package

I am currently working on creating a range of TypeScript packages as part of a Turborepo project. Here is an example of how the import structure for these packages looks like: import { Test } from "package-name" import { Test } from "package ...

Create a responsive iframe that expands to fullscreen when a button is clicked

Currently, I am using the following code to create an adaptive iframe with a fixed ratio for both width and height: <div id="game-container" style="overflow: hidden; position: relative; padding-top: 60%"> <iframe style="position: absolute; width ...

Not motivated to write HTML content

Recently, I've been utilizing the lazySizes plugin for optimizing my images. However, I encountered an issue when trying to implement it for HTML content display. Is there a simpler way to achieve this and maintain my current HTML structure? $(&apo ...

Angular's minimum date validation is not accurate for dates prior to the year 1901

Any assistance or clarification on this matter would be greatly appreciated. It appears that there may be an issue with my implementation, as otherwise it seems like a significant bug within Angular. Setup Create a form with a minimum date of 0001-01-01 ...

Receiving multiple NodeJS Responses through AJAX for a single request

I have been working on a WebApp that involves heavy AJAX calls from the frontend and NodeJS Express at the backend. Here is a glimpse of my Frontend Code- Below is the global AJAX function I consistently use in all my projects: function _ajax(params = {}, ...

Pulling information from a JSON file using Angular 2

Is there a way to extract data from a JSON file in an Angular 2 project? I attempted the following code snippet, but it seems to be ineffective. Perhaps I missed some important details... any guidance would be greatly appreciated. Additionally, I aim to s ...

Make sure to load all necessary resources prior to loading the webpage

My inquiry is as follows: I have a single webpage containing numerous images in both small and large resolutions, utilized in HTML and CSS (e.g., as background images in CSS classes). Currently, I am looking to preload all the images on my site before it ...

Utilizing the Vuetify pagination feature in your project

I am in need of some guidance regarding the configuration of vuetify pagination. I have a card component that I loop through, but I also want to implement pagination around it. Any insights on where to start would be greatly appreciated? <v-pagination ...

Changing the port number for a gulp-angular project with loopback REST API: A step-by-step guide

I'm currently working on a project that utilizes loopback for the backend and Angular for the frontend. My client side was set up with gulp-angular, and I added lb-services.js from loopback. The issue I am facing is that my Angular application is atte ...