Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

javascript - Manipulate JSON from TypeScript

I have the following JSON data.

[{'connectionId': 1, 'roomId': 140, 'connectionName': 'Hai'},
 {'connectionId': 1, 'roomId': 147, 'connectionName': 'Hai'},
 {'connectionId': 2, 'roomId': 100, 'connectionName': 'hello'},
 {'connectionId': 2, 'roomId': 140, 'connectionName': 'hello'}]

I want to retrieve response like the below from the above data using typescript

  [ { 'connectionId': 1, 'roomId': [ 140, 147] , 'connectionName': 'Hai'} 
  , { 'connectionId': 2, 'roomId': [ 100, 140] , 'connectionName': 'hello'} 
  ] 
   

How to solving this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

this way...

const data = 
      [ { connectionId: 1, roomId: 140, connectionName: 'Hai' } 
      , { connectionId: 1, roomId: 147, connectionName: 'Hai' } 
      , { connectionId: 2, roomId: 100, connectionName: 'hello' } 
      , { connectionId: 2, roomId: 140, connectionName: 'hello' } 
      ] 
  , result = data.reduce((a,{connectionId,roomId,...more})=>
      {
      let p = a.find(x=>x.connectionId===connectionId)
      if(!p)
        {
        p = { connectionId, roomId:[],...more}
        a.push(p)
        }
      p.roomId.push(roomId)
      return a
      },[])
      
console.log( result )
.as-console-wrapper { max-height: 100% !important; top: 0; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...