Reputation: 2412
I'm trying to populate an Immutable JS Map. Given an array of fields and a form, e.g.
{form: 'Register', fields: ['name','firstname']}
I'm trying to get something like:
{ form :
{ name: {
value: '',
hasFeedback: false
},
firstname: {
value: '',
hasFeedback: false
}
}
}
My current code:
let newState = state;
fields.forEach((field) => {
newState = newstate.setIn([form, field, 'value'], '');
newState = newstate.setIn([form, field, 'hasFeedback'], false);
});
return newState;
I'm new to the whole immutable thing: is this the right way of populating the Immutable Map? I'm a breaking any conventions on immutability? Is this the most elegant way?
Upvotes: 1
Views: 206
Reputation: 5715
I'm not aware of any conventions, but it might be better to create the desired structure first, and then convert it using Immutable.fromJS
. Applying mutations one-by-one, like you're doing now, will have some unnecessary overhead.
Possible refactoring of your code:
var form = fields.reduce((acc, f) => {
acc.form[f] = {
value: '',
hasFeedback: false
};
return acc;
}, {form: {}});
var immutableForm = Immutable.fromJS(form);
Upvotes: 2