Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I convert all elements of my form to a JavaScript object?

(如何将表单的所有元素转换为JavaScript对象?)

I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element.

(我希望有一些方法可以自动从表单中构建JavaScript对象,而不必遍历每个元素。)

I do not want a string, as returned by $('#formid').serialize();

(我不需要$('#formid').serialize();返回的字符串$('#formid').serialize();)

, nor do I want the map returned by $('#formid').serializeArray();

(,也不希望$('#formid').serializeArray();返回的地图)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
273 views
Welcome To Ask or Share your Answers For Others

1 Answer

serializeArray already does exactly that.

(serializeArray已经做到了。)

You just need to massage the data into your required format:

(您只需要将数据整理成所需的格式:)

function objectifyForm(formArray) {//serialize data function

  var returnArray = {};
  for (var i = 0; i < formArray.length; i++){
    returnArray[formArray[i]['name']] = formArray[i]['value'];
  }
  return returnArray;
}

Watch out for hidden fields which have the same name as real inputs as they will get overwritten.

(注意与真实输入同名的隐藏字段,因为它们会被覆盖。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...