首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery serializeArray()对

jQuery serializeArray()对
EN

Stack Overflow用户
提问于 2021-07-07 20:49:50
回答 1查看 32关注 0票数 0

我有以下JSON:

代码语言:javascript
复制
[
   {"name":"recid","value":"6028"},
   {"name":"notes","value":""},
   {"name":"recid","value":"6029"},
   {"name":"notes","value":""},
   {"name":"recid","value":"6030"},
   {"name":"notes","value":""},
   {"name":"recid","value":"6031"},
   {"name":"notes","value":""}
]

我就是这么做的吗?

代码语言:javascript
复制
      // Serialize form data
      var data = table.$('input,select,textarea').serializeArray();

      // Include extra data if necessary
      //data.push({'name': 'orderid', 'value': <%=orderid%>});

      alert (JSON.stringify(data));

我如何使数据看起来像这样:

代码语言:javascript
复制
[
   {"recid":6028,"notes":null},
   {"recid":6029,"notes":null}
]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-07 21:14:21

reduce循环可以帮助填充所需的数据。附有评论:

代码语言:javascript
复制
let data = incoming.reduce((b, a, i) => { // b is the accumlating array, a is the iteration, i is index
  let prev = i > 0 ? b.length - 1 : 0 // get the prev array index
  if (i > 0 && i % 2) b[prev][a.name] = a.value; // every other time add to the previous array object
  else b.push({ [a.name]: a.value }); // else start a new one
  return b
}, [])

代码语言:javascript
复制
let incoming = [{"name":"recid","value":"6028"},{"name":"notes","value":"test notes"},{"name":"recid","value":"6029"},{"name":"notes","value":"test notes2"},{"name":"recid","value":"6030"},{"name":"notes","value":"test notes3"},{"name":"recid","value":"6031"},{"name":"notes","value":"test notes4"}]

let data = incoming.reduce((b, a, i) => {
  let prev = i > 0 ? b.length - 1 : 0
  if (i > 0 && i % 2) b[prev][a.name] = a.value;
  else b.push({
    [a.name]: a.value
  });
  return b
}, [])

console.log(data)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68292830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档