Home > OS >  how to save two sets of ids as a set in an object like structure in javascript
how to save two sets of ids as a set in an object like structure in javascript

Time:08-05

I have a json response which looks like below. I want to save only the attachmentId and txnId from this as an object. How do I loop through this amd save in object? How do i do this in javascript?

  {
    date: '2022-07-18T17:08:00Z',
    attachmentId: 'a0722115-6f02-4995-9814-9cf48ff424e1',
    txnId: '9e6c83c6-3f6f-4023-855e-1c933f7af0bf',
    status: 'completed'
  },
  {
    date: '2022-07-18T16:53:10Z',
    attachmentId: 'e5795e12-2cb1-4051-a018-704cf19e0d0d',
    txnId: '06b37132-0aa0-49fa-b442-8afda800006d',
    status: 'completed'
  },
  {
    date: '2022-07-13T21:55:40Z',
    attachmentId: '0490414b-0c78-4335-8c7c-fa6f6f3a227e',
    txnId: '42a6e317-4e16-4cb4-a267-74c0c1c7d3b5',
    status: 'completed'
  }
]```

CodePudding user response:

To do this you need to map the array to the new values, in this case, an object with just the attachment id and txnID.

const data = [{
    date: '2022-07-18T17:08:00Z',
    attachmentId: 'a0722115-6f02-4995-9814-9cf48ff424e1',
    txnId: '9e6c83c6-3f6f-4023-855e-1c933f7af0bf',
    status: 'completed'
  },
  {
    date: '2022-07-18T16:53:10Z',
    attachmentId: 'e5795e12-2cb1-4051-a018-704cf19e0d0d',
    txnId: '06b37132-0aa0-49fa-b442-8afda800006d',
    status: 'completed'
  },
  {
    date: '2022-07-13T21:55:40Z',
    attachmentId: '0490414b-0c78-4335-8c7c-fa6f6f3a227e',
    txnId: '42a6e317-4e16-4cb4-a267-74c0c1c7d3b5',
    status: 'completed'
  }
]

const asObject = data.map(obj => ({attachmentId:obj.attachmentId, txnId:obj.txnId}))
console.log(asObject)

CodePudding user response:

    let a = [{
        date: '2022-07-18T17:08:00Z',
        attachmentId: 'a0722115-6f02-4995-9814-9cf48ff424e1',
        txnId: '9e6c83c6-3f6f-4023-855e-1c933f7af0bf',
        status: 'completed'
      },
      {
        date: '2022-07-18T16:53:10Z',
        attachmentId: 'e5795e12-2cb1-4051-a018-704cf19e0d0d',
        txnId: '06b37132-0aa0-49fa-b442-8afda800006d',
        status: 'completed'
      },
      {
        date: '2022-07-13T21:55:40Z',
        attachmentId: '0490414b-0c78-4335-8c7c-fa6f6f3a227e',
        txnId: '42a6e317-4e16-4cb4-a267-74c0c1c7d3b5',
        status: 'completed'
      }
    ]
let b  = []
a.forEach((obj,id)  => { b[id] = ({attachmentId,txnId} = obj, {attachmentId,txnId}) }) 
  • Related