Search code examples
typescriptobjectlodash

Transform Object to KeyValue pair Lodash


I have the below object [{"id":"123","username":"user1"},{"id":"456","username":"user2"}]

I want to transform it to below using lodash [{key: "123", value: "user1"}, {key: "456", value: "user2"]

Thank you for your help.


Solution

  • You can do any of the following:

    const data = [{ id: '123', username: 'user1' }, { id: '456', username: 'user2' }]
    
    // 1st
    const aa = data.map(x => {
      return {
        key: x.id,
        value: x.username
      }
    })
    console.log(aa)
    
    // 2nd
    const bb = data.map(x => ({
      key: x.id,
      value: x.username
    }))
    console.log(bb)