Home > Back-end >  Transform Object to KeyValue pair Lodash
Transform Object to KeyValue pair Lodash

Time:03-08

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.

CodePudding user response:

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)

CodePudding user response:

If your object is obj, then this would do the job, using lodash/fp module:

_.map(_.mapKeys(x => ({id: "key", username: "value"})[x]), obj)

where _.map is executing its first argument on every element of its second argument obj; x => _.mapKeys(/* stuff */) looks up the object that connects id/username to key/value with the given x.

  • Related