What is the best way to add an item to an array with distinct properties?

I am currently working on creating an array with different properties for each day of the week. Here is what I have so far:

const [fullData, setFullData] = useState([{index:-1,exercise:''}])

My goal is to allow users to choose exercises for a specific day, such as Monday, and store the selected exercises along with the corresponding weekday index. The desired output would look something like this:

[{index:1,exercise:'exercise1'},{index:1,exercise:'exercise2'}]

The challenge lies in properly integrating the existing exercise array and weekday variable into the code. The exercise values are stored in another array:

const [exerciseValues, setExerciseValues] = useState([]);

And the weekday index is stored as a regular variable:

let selectedWeekday_Index:number;

I have tried various solutions found on stackoverflow but have been unable to successfully implement them into my code. My latest attempt produced non-functional code. If further clarification is needed, feel free to ask and I will provide more details.

 const acceptExercises = () => {
    let selectedElements = [...exerciseValues]
    let savedData = [...fullData]
    
    selectedElements.forEach(element => {
      let copyData=savedData.map(item=>({
        [item.exercise]:element,
        [item.index]:selectedWeekday_Index
      }))
      setFullData(copyData)
    });
   }

Answer №1

To improve efficiency, I suggest considering a different method for saving your data as suggested by @iz_.

If you still prefer the current approach, you can utilize this code snippet to set your completeData:

const incorporateActivities = () => {
    setCompleteData((previous) => [
      ...previous,
      ...activityValues.map((activity) => ({
        position: selectedDay_Index,
        activity: activity,
      })),
    ]);
};

We start by duplicating the existing values using previous, then we iterate over the activityValues array to generate a list of activities with the appropriate day index. These are then spread and appended to the completeData.

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

Empowering your Angular2 application with data binding

I am currently working with the following template: <table width="700"> <caption>All Users</caption> <thead> <tr> <th>name</th> <th>surname</th> < ...

Encountered a problem when compiling Java with Javac for react-native-autogrow-textinput in DEBUG mode

On my Windows machine, I'm having trouble running a project that runs perfectly on my Mac device. When attempting to run the project, I encountered some issues. Below is a detailed screenshot of the error. Can someone please review it and assist me in ...

The component "react-native-snap-carousel" is having trouble displaying the card image

Recently, I started working with react native and encountered an issue while trying to implement the "react-native-snap-carousel". The carousel was functioning correctly with the data provided in the "carouselItems" array, but I faced difficulties with dis ...

Refreshing the page in React does not retain LocalStorage data when using Context

Managing state in my application using React Context and persisting data with LocalStorage has presented a challenge. Despite my efforts to maintain the stored data after a page refresh, I am facing an issue where the data is not retained as expected. here ...

Make sure the auto import feature in TypeScript Visual Studio Code Editor is set to always use the ".js" extension

At times, the auto-import completion feature includes the .js extension, but inconsistently. When this extension is missing in the TypeScript source, the emitted JavaScript file may encounter runtime issues like module not found error since the tsc compile ...

Unable to locate the reference to 'Handlebars' in the code

I am currently attempting to implement handlebars in Typescript, but I encountered an error. /// <reference path="../../../jquery.d.ts" /> /// <reference path="../../../require.d.ts" /> My issue lies in referencing the handlebars definition f ...

Deliver JSX components that match one or more keys in the array of strings

Seeking assistance and guidance here. It seems like I might be overlooking something obvious. I am attempting to create a component that accepts either a string or string Array string[] as a property. const ComponentThatReturnsElement = (someElementName) = ...

Encountering a type error while trying to read dummy data, as the map function is not

I am currently working on fetching dummy data from a URL in my component using TS and Next.js. Unfortunately, I encountered an error type that I am unable to diagnose. typings.d.ts: export type Themen = { id: number; title: string; description: string; ...

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

Sidenav Angular Material cdkScrollable is an effective tool for creating scrollable

In Angular Material CDK, there is a special Directive called CdkScrollable that allows you to monitor ScrollEvents within a specific container. I am currently attempting to retrieve the CdkScrollable associated with the default MatSidenavContent. Unfor ...

Even after ensuring the proper type checking, I am still receiving the error message "Property 'message' does not exist on type 'object'"

I have the following code snippet: try { // api call } catch (error) { if (typeof error === 'object' && error !== null && 'message' in error) { if (typeof error.message === 'string') { if (error.me ...

Interfaces and Accessor Methods

Here is my code snippet: interface ICar { brand():string; brand(brand:string):void; } class Car implements ICar { private _brand: string; get brand():string { return this._brand; } set brand(brand:string) { this. ...

Tips on implementing npm's node-uuid package with TypeScript

Whenever I attempt to utilize node-uuid in TypeScript, I encounter the following issue: Cannot find module uuid This error occurs when I try to import the uuid npm package. Is there a way to successfully import the npm uuid package without encountering ...

Converting an array with objects to comma separated strings in javascript using (ionic , Angular , NodeJS , MongoDB)

Retrieving specific data from an API array: let passions = [ {_id: "60a1557f0b4f226732c4597c",name: "Netflix"}, {_id: "60a1557f0b4f226732c4597b",name: "Movies"} ] The desired output should be: ['60a1557f0b4f226 ...

Methods for organizing consecutive elements within an array in Javascript/Typescript

Let's explore this collection of objects: [ { key1: "AAA", key2: "BBB" }, { key1: "BBB", key2: "CCC" }, { key1: "CCC", key2: "DD ...

What are the reasons and methods for cleaning up components in React JavaScript?

While I comprehend the necessity of tidying up our components in React to avoid memory leaks (among other reasons), as well as knowing how to utilize comonentWillUnmount (which is outdated) and the useEffect hook, my burning question remains: what exactl ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

Determine through programming whether an ng-content slot has been filled in Angular

I have developed a dynamic Angular component that utilizes content projection and slots in the following way: <div class="content-wrapper"> <div class="short-wrapper" [style.opacity]="expanded ? 0 : 1"> ...

Tips on showcasing an array as a matrix with a neat line property

I am currently developing an application using TypeScript, and utilizing a JSON array structured like this: data = [{"name":"dog", "line":1}, {"name":"cet", "line":1}, ...

What is the best method for calculating the total sum by multiplying the values in an array?

In my current project, I have an array consisting of multiple objects, each containing a property named "amount". My goal is to sum up all these amount values to get the total. Initially, I attempted to use a for loop but encountered an issue where settin ...