1

Good day everyone,

I need a help on how to submit an object with array of object inside and the array of object should be from a checkboxes I've made.

This is my sample checkbox

<input type="checkbox" name="user.preferences" value="Hard" />
<input type="checkbox" name="user.preferences" value="Soft" />
<input type="checkbox" name="user.preferences" value="Small" />

My data javascript looks like this:

user:{ 
    preferences: [] 
}

When I alert theuser using JSON.stringify, I can able to see a result something like this.

{"preferences": ["Soft","Small"]}

But the problem is, the api that I'm using needs a format like this:

{
    "preferences": [
     {
         "preference": "Hard"
     },
     {
         "preference": "Soft"
     },
     // so on and so forth
    ]
}

Please somebody help me. Thank you

2
  • are you processing this data or is it being sent directly by the form? Commented Oct 15, 2018 at 3:25
  • 2
    You should not have duplicate id attribute values in your HTML Commented Oct 15, 2018 at 3:26

1 Answer 1

6

You should .map each string in preferences to an object with that preference as its key/value:

const user = {
  "preferences": ["Soft", "Small"]
};
user.preferences = user.preferences
  .map(preference => ({ preference }));
console.log(user);

Sign up to request clarification or add additional context in comments.

2 Comments

But my another question is, how can I reverse it? from api to my javascript?
Just go the other way around: .map({ preference }) => preference)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.