Insert items into a frozen map

I'm dealing with an immutable map and iterating through an array to create objects that I want to place inside the map. What would be the correct approach to achieve this? Below is my current code snippet:

let arrayOfNames = ['John', 'Lisa'];

arrayOfNames.forEach(function(name) {
  let id = generateId();
  let newPerson = {
    id: id,
    name: name,
  };

  // people represents the immutable map
  people.set(id, newPerson);
});

The issue is that when I try to console.log(people), John and Lisa are not included in the output because people is immutable.

I have a solution for inserting one element into the map and assigning it to a new variable:

let newPeople = people.set('3', {id: 3, name: 'John'});

But how can I handle this when I need to iterate through multiple elements?

Answer №1

To properly update the people variable within a loop, you need to ensure it is reassigned each time.

let people = ... // make sure to use let instead of const

arrayOfNames.forEach(function(name) {
  let id = generateId();
  let newPerson = {
    id: id,
    name: name,
  };

  // Here, we are updating the immutable map stored in the 'people' variable
  people = people.set(id, newPerson);
});

let people = new Immutable.Map();

['Alice', 'Jane'].forEach((name, id) => {
  people = people.set(id, {id, name})
})

console.log(people)

// or using reduce

const people2 = ['John', 'Peter'].reduce((map, name, id) => map.set(id, {id, name}), new Immutable.Map)

console.log(people2)
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c25212139382d2e20290c7f6274627d">[email protected]</a>/dist/immutable.js"></script>

Answer №2

To take a different approach, you could start by "preparing" the new people map and then combining it with the current map.

For example:

const freshPeopleMap = Immutable.Map(['John', 'Lisa'].map(function(personName) {
    let id = generateId();
    let newPerson = {
        id: id,
        name: name,
    };

    return [id, newPerson];
}));

const combinedPeopleMap = people.merge(freshPeopleMap);

By following this method, you maintain immutability, which is likely the reason you are utilizing Immutable.js in the first place. ;)

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

Utilize communication channels to access electron's main process functions from the render process once deployment is complete

Hey there, I'm facing a challenge with accessing methods from my index.js main process in the render process. I've experimented with two different approaches to solve this issue. ipcMain and ipcRender Initially, I attempted to utilize ipcMain an ...

Please ensure the public_id parameter is included and provide the necessary value for the imageId when working with Cloudinary

I am in the process of developing a website where users can share insights and comments on novels they have read. Users have the option to include images of the novel with their posts or not. If an image is included, the post schema requires attributes im ...

Utilizing precise data types for return values in React hooks with Typescript based on argument types

I developed a react hook that resembles the following structure: export const useForm = <T>(values: T) => { const [formData, setFormData] = useState<FormFieldData<T>>({}); useEffect(() => { const fields = {}; for (const ...

The state variables of React components do not always retain their most recent value

Currently, I am working on implementing the functionality of an event based library called powerbi-client-react. The first step involves retrieving the component using getEmbeddedComponent and storing it in the variable report. Then, I need to utilize the ...

AngularJS is encountering an issue where it cannot locate the App Module

Whenever I attempt to execute this code, I encounter errors. Below is the code followed by the error message: index.html: <!DOCTYPE html> <html> <head> <meta id="meta" name="viewport" content="width=device-width, initial-scale=1 ...

Obtaining a JavaScript object reference within a jQuery callback

Consider the following code snippet: var CustomClass = function(id){ this.id = generateUniqueID(); this.element = jQuery("#"+id); this.setupClickEvent(); }; CustomClass.prototype = { setupClickEvent: function(){ var s ...

Error: The process.binding feature is not supported in the current environment (browserify + selenium-webdriver)

Recently, I've been attempting to execute a Node.js code on the client side of my browser. To make my code compatible with browsers, I am using Browserify for conversion purposes. Below is the command I use for this transformation: browserify te ...

Refreshing webpage content by utilizing iframes

I am looking for a way to completely clear a webpage using either Javascript or PHP. However, there seems to be an issue with a specific area of the page that is marked as: data-form="manual iframe" When attempting to clear the page, only the data within ...

Retrieving data from a different thread in JavaScript

After coming across this code snippet, I decided to try it out but faced some challenges. The function "IsValidImageUrl()" is meant to provide an instant result, however, due to running in a separate thread, retrieving the value proved difficult. Even with ...

Canvas image zoom and crop feature ensures fixed selection area across all platforms

After finding inspiration from a source I cannot name, I developed a plugin that allows for image cropping on both mobile and desktop devices. The key features of my plugin include touch support, dynamic canvas sizing based on image dimensions, and the ab ...

Error encountered with STRIPE PAYMENT GATEWAY: "Customer cus_xxxx is missing card with ID tok_visa"

// client side code const onToken = async (token) => { console.log(token); const bookingDetails = { room, userid: JSON.parse(localStorage.getItem("currentUser"))._id, fromdate, todate, totalAmount, totaldays: totalDays, token, }; try { ...

Transform your HTML audio player into a Vue component

I am in the process of converting an HTML player into a Vue component. Half of the component has been successfully converted, but the time control slider is still missing. Below is the original HTML code for the player: // JavaScript code for the audi ...

Keeping Record of Assurances

I'm currently working on a project where I need to track Promises effectively. Within the project, there are some lingering async tasks that haven't been properly awaited or yielded. Identifying and addressing these cases is crucial as they are ...

Developing a customizable datepicker with the ability to select specific months or date ranges

I am currently developing a WebApp using flask and constructing templates in HTML/JS for the front end. I am in need of a datepicker that will provide the user with the option to choose a specific date range or select a range of months. Take a look at the ...

Is it possible to use ref in React to reference various elements based on specific actions?

I'm having trouble targeting the clicked button using a ref as I always get the second one. Any ideas on how to solve this issue? Also, if I have a native select element with two optgroups, is it possible to determine from which optgroup the selection ...

Issue with AnimeJS Motion Path causing element to deviate from desired SVG path

I'm attempting to use an SVG element and the AnimeJS library to make the orange marker follow the course of this RC car race track. https://i.stack.imgur.com/8FKHC.png Despite my efforts, I am encountering strange and undesirable outcomes. At times ...

Utilize the ConditionExpression to update the status only when the current status is not equal to 'FINISH'

I'm struggling to create a ConditionExpression that will only update the status in my DynamoDB table called item. Here's what I have so far: dynamo.update({ TableName, Key, UpdateExpression: 'SET #status = :status', Exp ...

The execution of a function within context is not triggered

I have developed a decentralized application (dApp) that utilizes a context folder to interact with a smart contract. Within the context, there is a function named loadAuth which verifies if the user is authenticated and then assigns the account state to u ...

Arrow function in JSX syntax within a render method

After stumbling across this code snippet in a different question, I'm left scratching my head over how it actually functions: let Parent = () => ( <ApiSubscribe> {api => <Child api={api} />} </ApiSubscribe> ) I can gr ...

Tips for effectively linking a ReactJS component to Redux with the help of react-redux

Currently, I am in the process of establishing my initial connection between a React component and Redux in order to fetch data from my node API. Although this component is currently simple, it has potential for expansion to include subcomponents that wil ...