Using the spread operator in Typescript/Javascript to dynamically add members to an object based on certain conditions

I was exploring a method for conditionally adding members to an object, which I found here

Below is the code I came up with:

const theobj = {
    field1: "hello",
    field2: 1,
    data: {
        datafield1: "world",
        datafield2: 2
    },
    field3: "yowzee"
};

let someobj: any;
someobj = theobj;

const test = {
    ...(someobj.field1 &&  {field1: someobj.field1}),
    ...(someobj.nofield && {nofield: "yowzee"}),
    ...(someobj.data?.datafield1 && {data: {dataField1: "woohoo"}}),
    ...(someobj.data?.datafield2 && {data: {datafield2: "hooahh"}}), // overwrites the above   
};

console.log(test);

The only issue I encountered is that the last conditional statement overwrites data.datafield1. It seems to recreate the inner data objects. Any suggestions on how to fix this?

Answer №1

Aha, it's exactly what you're thinking - that's why having a reference from a previous value of the data object is crucial.

const test = {
    ...(someobj.field1 && { field1: someobj.field1 }),
    ...(someobj.nofield && { nofield: "yowzee" }),
    ...(someobj.data.datafield1 && { data: { dataField1: "woohoo" }}),
    ...(someobj.data.datafield2 && { data: { ...someobj.data, datafield2: "hooahh" }}), // ensures it doesn't overwrite the above.
};

By spreading someobj.data within itself, you maintain its previous value intact.

Answer №2

In the final line, you are assigning a new object to the data property of the current object, specifically {datafield2: "hooahh"}.

This action is similar to:

{
  data: { a: 1 }
  data: { b: 2 }
}

However, since duplicate keys override each other, it simplifies to:

{
  data: { b: 2 }
}

If you wish to assign data as a single object with conditional sub-keys, you can achieve this by:

const test = {
    ...(someobj.field1 &&  {field1: someobj.field1}),
    ...(someobj.nofield && {nofield: "yowzee"}),
    ...(someobj.data && {data: {
        ...(someobj.data.datafield1 && {dataField1: "woohoo"}),
        ...(someobj.data.datafield2 && {dataField2: "hooahh"}),
    }}),
};

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

Enhancing Javascript with ES6 for nested for loop operations

Hey there, I have a question about converting a nested for loop into an Array map/ES6 way. How does that work when dealing with nested for loops? for (var i = 0; i < enemy.ships.length; i++) { for (var n = 0; n < enemy.ships[i].locat ...

Uncovering the secrets of accessing req.body through expressjs

I'm having trouble accessing the body when receiving an expressjs request Here is my main server.js file: app.use(express.urlencoded({extended: true})); app.use(express.json()); app.use(router); And this is my router.js file: ...

Obtain the Encoded Data

Unfortunately, I do not have control over domain.com. However, I am able to provide a redirect URL parameter like the one shown below: www.domain.com?retUrl=www.example.com%3Fparameter%3Dvalue Following the provision of retURL (www.example.com?parameter= ...

A step-by-step guide on utilizing the reduce function to calculate the overall count of a user's GitHub repositories

I need help finding the total number of repositories for a specific user. Take a look at my code below: Javascript const url = "https://api.github.com/users/oyerohabib/repos?per_page=50"; const fetchRepos = async () => { response = await f ...

Express (generator) is failing to load custom scripts located in the public folder

I'm new to node and express and I'm facing a problem. I want to load a custom script.js from the public folder, but it's not loading. There are no errors in the console or anything in the network tab. When I try to access the URL localhost:3 ...

Modifying the Redux state using an array with prototypes

In my React application, I am utilizing Redux along with the ChartJS library to create charts. Occasionally, when I extract an array from the global Redux state, it appears in this format: ejeY: Array(7) 0: 43783 1: 85001 2: 100960 3: 752 ...

Troubleshooting issues with data parsing in an Angular typeahead module

Utilizing the AngularJS Bootstrap typeahead module, I am attempting to showcase data from an array of objects. Despite receiving data from my API call, I keep encountering the following error: TypeError: Cannot read property 'length' of undefine ...

The type "AppRouterInstance" cannot be assigned to type "nextRouter"

Within my Next.js project, a registration form is included as seen below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form" ...

Discover the magic of using the spread operator to effortlessly insert key-value pairs into an object!

Currently, I am grappling with the challenge of handling variable products using the spread function. For instance, in an online store selling clothes (similar to the screenshot linked below), I am looking to track when a user adds different sizes of the s ...

"Textarea auto-resizing feature causes an excessive number of unnecessary lines to be added

I have a textarea that is coded with jQuery to limit the characters to 11 per line and automatically resize based on the number of lines. However, when users click 'Enter' to add a new line, it adds multiple extra lines instead of just one. This ...

Inquiries prior to projecting rays

As I delve into the world of Interaction with Three.js, several questions arise in my mind. 1) Can you shed some light on what exactly Viewport Coordinates are? 2) In what ways do they differ from client Coordinates? 3) How did we come up with this form ...

Finding all elements with a specified attribute in jQuery: A comprehensive guide

While looking for an example, I came across one that searches only inputs instead of all elements: https://api.jquery.com/attribute-equals-selector/ Is there a way to modify this example so that it can search all elements in the DOM, and not just inputs ...

Expanding IntelliSense and helpful tooltips in VSCode for JavaScript and TypeScript by utilizing Node.js for a deeper understanding

As a beginner in programming, specifically in JS/TS, I've been experimenting with node.js and have encountered a puzzling issue with the IntelliSense or 'helptext' feature in VSCode. For instance, when attempting to use fs.open(), I receive ...

I am in need of a efficient loader for a slow-loading page on my website. Any recommendations on where to find one that works

I'm experiencing slow loading times on my website and I'm looking to implement a loader that will hide the page until all elements are fully loaded. I've tested several loaders, but they all seem to briefly display the page before the loader ...

Mistakes encountered when utilizing the Gremlin DSL in the `repeat` stage

Our team is utilizing gremlin-javascript and has recently implemented a DSL (Domain Specific Language) to streamline our queries. However, we have encountered an issue when trying to use DSL methods within a repeat step. Every time we attempt this, we con ...

"PHP and Javascript Validation Library: Building Confidence in Your Data

Looking for a PHP form validation library that can work independently outside of any PHP framework? It should be able to handle basic validations like checking for empty fields, using regex, validating email addresses, and alphanumeric characters. Ideally, ...

The Vue.js transition feature seems to be malfunctioning when trying to display a modal

I can't figure out why my animation isn't working with Vue transitions. Here is the code I have: <template> <teleport to="body"> <div class="modal-overlay" v-if="loading"> <transitio ...

Tips for aligning text vertically in flexbox arrangements

As I work on building my portfolio, I have implemented links as buttons using flexbox to make responsiveness easier. The height of these flexboxes is set dynamically using JavaScript with percentages. Despite trying various suggestions, none of them provi ...

Deleting an element from an array stored in local storage with the help of jQuery

Summary: Developing a front-end wish list feature Tech Stack: Utilizing HTML5 (localStorage), CSS, and jQuery Key Features: Ability to add and delete items dynamically with real-time count display Challenge: Issue encountered when trying to remove added ...

If the iframe's CSS source is updated, the parent's CSS source will also change

I'm currently working on a unique school project that involves creating multiple CSS styles for different views. <link rel="stylesheet" type="text/css" href="css/main.css" title="main" media="screen"> <link rel="stylesheet" type="text/css" h ...