我有这个对象.
var orig_array = [ { "MSG_ID": { "lgth": "1","payload": 0 } },{ "STATE_1": { "lgth": "1","payload": "XX" } },{ "STATE_2": { "lgth": "1","payload": "XXX" } },{ "MSG_ID": { "lgth": "1","payload": 1 } },"payload": "X" } },{ "STATE_3": { "lgth": "6","payload": 2 } },"payload": "XXXX" } } ];
生成的数组应如下所示;
var processed_array = [ { "MSG_ID": { "lgth": "1","payload": 0 },"STATE_1": { "lgth": "1","payload": "XX" },"STATE_2": { "lgth": "1","payload": 1 },"payload": "X" },"STATE_3": { "lgth": "6","payload": 2 },"payload": "XXXX" } } ];
在orig_array中,有3个对象具有“MSG_ID”.随后的“STATE_X”对象被组合到上面的“MSG_ID”对象中.我已经盯着这个问题一段时间了.任何人都可以帮助或提供一些提示作为先发制人?
解决方法
您可以使用
Array#reduce
并查找“MSG_ID”作为组更改.
var array = [{ "MSG_ID": { "lgth": "1","payload": "XXXX" } }],grouped = array.reduce(function (r,a) { var key = Object.keys(a)[0]; if (key === 'MSG_ID') { r.push({}); } r[r.length - 1][key] = a[key]; return r; },[]); console.log(grouped);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。