0

I am passing a string from view to controller. Here's my ajax code

    var formData = $('#spec-wip-form, #platingspec-form').serializeArray();
    var platingId = @Model.PlatingId;

    var form = JSON.stringify(formData);
    $.ajax({
        url: "/Specifications/Edit",
        type: 'PUT',
        data: { form, cleaningProcess, platingId },
        success: function () {
            onUpdated();
        }
    });

The JSON format I'm getting looks like this

"[{\"name\":\"PlatingId\",\"value\":\"1\"},{\"name\":\"DivisionId\",\"value\":\"79\"}]

I want it to look like this

"[{\"PlatingId\":\"1\"},{\"DivisionId\":\"79\"}]

I already tried this earlier but

var formData = $('#spec-wip-form, #platingspec-form').serialize();

I get

formData: PlatingId=1&DivisionId=79&

How can I do it?

asdf
  • 33
  • 1
  • 10

2 Answers2

0

Thanks to @SebastionSimon for the correction. Also, this isn't double stringified to match your expected result. You can always run it through JSON.stringify a second time to match.

let json = '[{"name":"PlatingId","value":"1"},{"name":"DivisionId","value":"79"}]';

let newjson = JSON.stringify(
    JSON.parse(json).map(
        ({name, value}) => ({[name]: value})
        ))

console.log(newjson)
Kinglish
  • 23,358
  • 3
  • 22
  • 43
-2

You can use Object.fromEntries() to create a single object.

const formData = [{"name":"PlatingId","value":"1"},{"name":"DivisionId","value":"79"}];

const res = Object.fromEntries(formData.map(({name,value})=> [name, value]));

console.log(res)
charlietfl
  • 170,828
  • 13
  • 121
  • 150