Creating object properties dynamically based on specific conditions

Is there a more efficient way to create object properties that are dependent on certain conditions? For example, one can define a variable based on a condition like this:

const foo = someCondition ? true : undefined

However, what I am seeking is to achieve something like the following in pseudo code:

const foo = {
  someCondition ? { a: true }
  b: 'b' 
}
// returning { a: true, b: 'b' } if someCondition is met or { b: 'b'} if not.

One approach to tackle this is through:

const foo = { ...someCondition ? { a: true }: {}, ...{ b: 'b'} }

Nevertheless, I find this solution involving the creation of intermediate objects and their merging into a new object to be suboptimal in terms of performance.

Another option could be:

const foo = { b: 'b'}
if(someCondition) foo.a = true

This method, while functional, separates the process of object creation into multiple steps, which is not ideal.

Yet another possibility:

const foo = { b: 'b'}
if(someCondition) Object.defineProperty(foo,'a',{ value: true})

Similar to the previous solution.

I'm curious if any of you have discovered a better way to accomplish this task than the ones I have tried?

Answer №1

By utilizing prototypes, you can achieve it in the following way:

let myBool = true;

function Obj() {
    if (myBool) this.myConditionedProp = "5"
}

let myObj = new Obj()

You also have the option to directly input parameters in the prototype function:

function Obj(age) {
    this.name = 'John'
    if(age) this.age = age
}

let myObj = new Obj(15)

console.log(myObj.name, myObj.age)

This approach has the advantage of not separating the object creation process, although it may not necessarily simplify it further.

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

Generating a two-dimensional array and setting its values in JavaScript

I need assistance with creating and initializing a two-dimensional array in JavaScript within an AngularJS application. My current approach is as follows: $scope.invalidVote = []; for (var i = 0; i < $scope.arry1.length; i += 1) { $scope.answersCou ...

Troubleshooting the problem of divs overlapping when scrolling in JavaScript

I am experiencing some issues with full screen divs that overlay each other on scroll and a background image. When scrolling back to the top in Chrome, the background shifts down slightly, and in Safari, the same issue occurs when scrolling down. I have cr ...

Eliminate square brackets from URL containing an array of IDs using Request.js

My nodejs express application is sending requests with an array parameter, but it's including '[]' in the query string: For example: /foo?id=1&id=3&id=5 How can I remove the square brackets '[]' from the query string? va ...

Sending data from an element within an ngFor loop to a service module

In my component, I have a loop that goes through an array of different areas with unique IDs. When you click the button, it triggers a dialog containing an iframe. This iframe listens for an event and retrieves data as JSON, then sends it via POST to an IN ...

The Intersection Observer API is caught in a never-ending cycle of rendering

I am experimenting with the intersection observer API in order to selectively display elements in a CSS grid as the user scrolls, but I seem to have run into a problem of encountering an endless rendering loop. Below is the code snippet I am working with. ...

Asynchronous JavaScript combined with a for loop

I'm interested in accomplishing a straightforward task using Nodejs and Async. Let's say I have a total of pages, which is 4 in this example. I am looking to send a request 4 times and then execute a callback once all responses have been receive ...

Is there a way to use JavaScript or jQuery to identify if Firefox is blocking mixed content

Is there a way to detect when Firefox (or any browser) is blocking mixed content using JavaScript or jQuery? To learn more about Firefox's mixed content blocking feature, visit: The backstory: My company has an external vendor that handles the onli ...

What could be causing the incorrect output when an else statement is included?

When I run the code provided below, I am getting a different answer depending on whether the else statement is included or not. Without the else statement, the answer is true, but with the else statement it is false. Can anyone explain why this is happen ...

What is the best way to send the link's ID to an AngularJS controller?

I have a scenario similar to the following: <a href="#" title="Post 1" id="car1"> Audi car </a> <a href="#" title="Post 1" id="car2"> BMW car </a> How can I pass the ID to the controller? I attempted the following: <a href= ...

Encountering a module resolve error when a tsx file is added to the project item group

After setting up an asp.net core project with a react template and configuring Typescript, I created a simple file named Test.tsx with the following code: import React from 'react'; class Test extends React.Component { render() { r ...

What are some effective ways to analyze jQuery and JavaScript using web development tools?

I'm struggling to use web development tools to inspect the JavaScript on websites. It's challenging to identify which parts of a site are utilizing JS, unlike CSS or HTML where it's more visibly defined. Even when I attempt to delete some J ...

Javascript Flickering Effect in HTML5

Currently, I am in the process of creating a simple game using javascript without jQuery. However, I am facing an issue with flickering on the canvas due to the clearing command. After researching solutions online, I came across suggestions for implementin ...

Deploy Node.js on a Debian server hosted on Google Compute Engine

Currently, I am operating a Debian server on Google Compute Engine using a host called example.com. My goal is to run a node.js app within a specific directory on this server, for instance, example.com/mynodeapp. Fortunately, the necessary components such ...

Asynchronous redux error: it is not permitted for modifiers to generate actions

Every time I try to dispatch a series of async actions to fetch assets from URLs, I encounter what seems to be a parallel async Redux error. I initially attempted to use the redux-thunk middleware but faced the same issue. Subsequently, I switched to a "l ...

Converting the beginning and ending dates of an event object in FullCalendar: A guide

After clicking on an event in FullCalendar and extracting the start and end date properties of the event, I encountered the following result: Just a reminder: I implemented the eventClick function as per the guidelines provided in the FullCalendar Documen ...

Perform a Selenium action to click on each individual HTML 'a' tag on

I am attempting to automate clicking on all the "a" tags within a website using Selenium in Python. However, I found that all the "a" tags I want to click have the same structure as shown in the code snippet below. I tried clicking them by their class si ...

Node.js server only supports cross-origin requests for protocol schemes when working with an Angular front end

Struggling to configure CORS on a local site hosting a Node.js server and an Angular client. Encountering the following error: Access to XMLHttpRequest at 'localhost:3000/api/v1/users' from origin 'http://localhost:4200' has been bl ...

Certain Font Awesome icons are not displaying properly in HTML

Currently facing an issue while developing my BlogApp. The problem at hand :- Attempting to utilize font awesomes fas fa icons, but some of them are not displaying properly. For example, class="fas fa-crown". When trying to access fas fa-crown ...

Optimal method for accessing params and queryParams in Angular 2

Seeking insights on how to craft a route with information stored in its URL parameters. Here's an example of my route (app.routes.ts): {path: 'results/:id', component: MyResultsComponent}, How I navigate to the route : goToResultsPage(qu ...

Using a static string in Javascript yields no issues, whereas working with variables can sometimes cause problems

I've been struggling with a problem this morning and it's time to ask for help! I have a JavaScript function that takes the value entered by a user into an autocomplete box, uses AJAX to send that value to a PHP script which then queries the data ...