这是json格式
[ { baseurl: 'http://localhost:5051/springbootdemo/getServerData',
server: '1' },
{ baseurl: 'http://localhost:5052/springbootdemo/getServerData',
server: '1' },
{ baseurl: 'http://localhost:5053/springbootdemo/getServerData',
server: '2' },
{ baseurl: 'http://localhost:5054/springbootdemo/getServerData',
server: '2' } ]
我想以这种形式重新安排
[
{server:1 , urls: [
"http://localhost:5051/springbootdemo/getServerData",
"http://localhost:5052/springbootdemo/getServerData"
]},
{server:2 , urls: [
"http://localhost:5053/springbootdemo/getServerData",
"http://localhost:5054/springbootdemo/getServerData"
]}`enter code here`
]
我想要上述格式的重新安排。
答案 0 :(得分:0)
首先,它不是JSON-它是一个普通数组。其次,您可以像这样使用reduce
:
const arr = [{baseurl:'http://localhost:5051/springbootdemo/getServerData',server:'1'},{baseurl:'http://localhost:5052/springbootdemo/getServerData',server:'1'},{baseurl:'http://localhost:5053/springbootdemo/getServerData',server:'2'},{baseurl:'http://localhost:5054/springbootdemo/getServerData',server:'2'}];
const res = Object.values(arr.reduce((a, { baseurl, server }) => {
(a[server] = a[server] || { server: +server, urls: [] }).urls.push(baseurl);
return a;
}, {}));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }