-2

this is the json format

[ { 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' } ]

i want to re arrange it in this form

[
  {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`
]

I want the re arrangement in above format.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 1
    Welcome to StackOverflow! Have you tried anything so far? StackOverflow isn't a free code-writing service, and expects you to [try to solve your own problem first](http://meta.stackoverflow.com/questions/261592). Please update your question to show what you have already tried, showing the specific problem you are facing in a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve). For further information, please see [how to ask a good question](http://stackoverflow.com/help/how-to-ask), and take the [tour of the site](http://stackoverflow.com/tour) – Jaromanda X Jul 08 '19 at 06:16

1 Answers1

0

Firstly, that's not JSON - it's an ordinary array. Secondly, you can use reduce like so:

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; }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79