Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 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 Reply

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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...