loganathan
loganathan

Reputation: 6136

reduce function with empty object is not working

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

Answers (2)

nem035
nem035

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

Nenad Vracar
Nenad Vracar

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

Related Questions