我有以下JSON:
[
{"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":""}
]我就是这么做的吗?
// 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));我如何使数据看起来像这样:
[
{"recid":6028,"notes":null},
{"recid":6029,"notes":null}
]发布于 2021-07-07 21:14:21
reduce循环可以帮助填充所需的数据。附有评论:
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
}, [])
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)
https://stackoverflow.com/questions/68292830
复制相似问题