Reputation: 6136
I'm trying to create object from form elements. For some reason, it is throwing the error.
let allInputs = [...formData];
allInputs.pop(); //Remove submit button
return allInputs.reduce((userObj, data) => userObj[`${data.name}`] = data.value, {});
Error
userModel.js:17 Uncaught TypeError: Cannot create property 'last_name' on string ''
Upvotes: 2
Views: 1821
Reputation: 35481
The problem is what you're returning the second time your reducer is called, not what you start with.
You are returning an assignment but should return an object.
(userObj, data) => userObj[`${data.name}`] = data.value // <-- this returns the result of the assignment
Something like this should work:
allInputs.reduce(
(userObj, data) => Object.assign(userObj, {
[data.name]: data.value
}),
{}
);
Note: as mentioned by Vic in the comment, no need for string interpolation, i.e. ${data.name}
-> just data.name
is enough.
Upvotes: 3
Reputation: 122037
You need to return accumulator or in your case userObj
in each iteration of reduce so your code should look like this.
allInputs.reduce((userObj, data) => (userObj[`${data.name}`] = data.value, userObj), {});
Upvotes: 5