0

I have a JSON object in jquery like this :-

userObj =
{ 
 "loginId":"abc123", 
 "class":"5", 
 "email":"[email protected]", 
 "level":"1"
}

I have to send a POST request to the server with multipart/form-data. I have created a FormData object :-

var fd = new FormData(); 

What I need to do is to iterate over each element in the JSON and append them to my variable fd. This is what I want :-

fd.append('loginId','abc123');
fd.append('class',5);
fd.append('email','[email protected]');

Any idea how to achieve this?

5 Answers 5

1

You can iterate the object using for

for (var key in userObj) {
  fd.append(key, userObj[key]);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

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

1 Comment

Thank you. I get the data on the server side. But the last element was a nested JSON element :-"userRole":{ "role":"STU", "level":"1" }, which doesn't go through. UserRole is null on the server-side whereas it should have been {"role":"STU", "level":"1"}
1

You can do it like this:

let userObj = { 
 "loginId":"abc123", 
 "class":"5", 
 "email":"[email protected]", 
 "level":"1"
};

let fd = new FormData();

for (let key in userObj){
    fd.append(key, userObj[key])
}

Comments

1
var userObj = {
    "loginId": "abc123",
    "class": "5",
    "email": "[email protected]",
    "level": "1"
};
var keys = Object.keys(userObj);
var values = Object.values(userObj);
var fd = new FormData();
for (var i = 0; i < keys.length; i++) {
    fd.append(keys[i], values[i]);
}

Comments

1

var userObj =
{ 
 "loginId":"abc123", 
 "class":"5", 
 "email":"[email protected]", 
 "level":"1"
}
var fd = new FormData(); 
$.each(userObj, function(i, val) {
  console.log(i + " " + val);
  fd.append(i, val);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

Try something like this.

Comments

0

let userObj = { 
 "loginId":"abc123", 
 "class":"5", 
 "email":"[email protected]", 
 "level":"1"
};

var newdata= new FormData();

 $.each(userObj, function (key, value) {
    newdata.append(key, userObj[key]);
    console.log(key, userObj[key])
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Comments

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.