1

I have an html form, a button and a click handler to manage the submission of the form. Question is specifically about the handler of the button to submit the form via AJAX.

This is the handler I wrote:

JS:

            $('#create').click(function(event) {
                console.log('Create Button Click');
                var dataJSON = JSON.stringify( $('#customer_form').serializeArray() );
                console.log(dataJSON);
                $.ajax({
                    type: "POST",
                    url: "/customer/",
                    // The key needs to match your method's input parameter (case-sensitive).
                    data: dataJSON,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data){
                        console.log('Success');
                        console.log(data);
                    },
                    failure: function(errMsg) {
                        console.log('Error');
                        console.log(errMsg);
                    }
                });
                event.preventDefault();
            });

I have used JSON.stringify( $('#customer_form').serializeArray() ); to generate the JSON string, getting as result -as shown by console.log(dataJSON):

[{"name":"name","value":"n"},{"name":"address_line_1","value":"a1"},{"name":"address_line_2","value":"a2"},{"name":"town","value":"t"},{"name":"postal_code","value":"p"},{"name":"region","value":"r"},{"name":"phone_1","value":"p"},{"name":"phone_2","value":"pa"},{"name":"fax","value":"f"},{"name":"email","value":"e"},{"name":"web","value":"w"}]

Which would be the easiest way to get the following structure:

[{"name": "n", "address_line_1": "a1", "address_line_2": "a2", "town": "t", "postal_code": "p", "region": "r", "phone_1": "p", "phone_2": "pa", "fax": "f", "email":"e", "web": "w"}]
4
  • if you really want that I suspect you have to write it yourself. But can you not submit this as normal form data? In which case you can just use data: $('#customer_form').serialize() and it should send something equivalent. Depends what your server accepts, but lots of frameworks accept either JSON or serialised form data. Commented Jan 8, 2018 at 15:35
  • @cale_b serialise() doesn't produce JSON, it produces a querystring, which can't easily be converted into JSON either. Not equivalent. See my comment above though because it's possible the server might accept that anyway. Commented Jan 8, 2018 at 15:36
  • My backend is a custom web service in Python -nameko framework-. I would like to process stuff in JSON as service might well receive requests from another processes. But information about serialize and that a JSON can't be "directly" be generated from the front-end in JS is quite useful Commented Jan 8, 2018 at 18:59
  • well, to be pedantic, it can be generated automatically, it's just not in the structure you wanted, that's all. And of course, it's possible to write your own routine to produce the output you'd prefer. Commented Jan 9, 2018 at 10:11

2 Answers 2

2

Something like this should work.

let obj = {}
for (let object in array) {
    obj[object['name']] = object['value']
} 
Sign up to request clarification or add additional context in comments.

6 Comments

Code-only answers aren't as useful, can you add an explanation / comments in the code to explain what you are doing?
Also worth mentioning that let is ES6 only, and may want / need to use var for compatibility with IE10 and some other browsers.
@cale_b I don't think is necessary to explain obvious things like let usage.
I was totally unaware about let and var differences. I thought in JS var defined a variable. I guess I shall use let in this context as the variable is intented to be used only within that context/block.
Here you can see everything explained in details. stackoverflow.com/questions/762011/…
|
0

var arr = [{"name":"name","value":"n"},{"name":"address_line_1","value":"a1"},{"name":"address_line_2","value":"a2"},
{"name":"town","value":"t"},{"name":"postal_code","value":"p"},{"name":"region","value":"r"},{"name":"phone_1","value":"p"},{"name":"phone_2","value":"pa"},{"name":"fax","value":"f"},{"name":"email","value":"e"},{"name":"web","value":"w"}];

var acc = {};
//firstly lets flat your name and value to one new object
var newArr = arr.map(item=>{
                  var newItem={};
                  newItem[item.name] = item.value;
                  return newItem;
                });
     
//secondly we reduce flat all rows inside the newArr..
//..to one unique object acc   
newArr.forEach(item=>{
    Object.keys(item).forEach(key=> acc[key] = item[key]); 
});
 
//now you one unique object which you can serve..
// inside a new array [acc]
console.log([acc])
 

 

1 Comment

It is useful but I find easier to Nikola's answer easier to follow and read.

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.