1

I'm trying to format the JSON response to the new format.

What would be the best approach to bring the expected results.

JSON RESPONSE

{
  body: [{
    id: 0,
    data: [{
        cellId: 0,
        colId: 'A',
        value: '*',
      },
      {
        cellId: 1,
        colId: 'B',
        value: 'W',
      },
      {
        cellId: 2,
        colId: 'C',
        value: 'ECE',
      }
    ],
    errors: [
      { colId: 'B', errorCode: 'msg_000' },
      { colId: 'D', errorCode: 'msg_001' }
    ]
  }]
}

Expected format after conversion is

const convertedData = {
  id: 0,
  A: '*',
  B: 'W',
  C: 'ECE'
  errors: [
    { colId: 'B', errorCode: 'msg_000' }, 
    { colId: 'D', errorCode: 'msg_001' }
  ]
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Murali
  • 43
  • 4
  • 3
    You need to show what you have attempted already. – Tibrogargan Nov 13 '19 at 06:50
  • [JSON](https://json.org) is a text representation of some data structure. That data structure is what you want to get, not to format the JSON. And TypeScript is not involved in the question. – axiac Nov 13 '19 at 06:50
  • Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output. – mplungjan Nov 13 '19 at 06:51
  • `let { id, errors } = obj.body[0]; let data = { id, errors }; obj.body[0].data.forEach(d => data[d.colId]=d.value) ` – mplungjan Nov 13 '19 at 07:01

1 Answers1

3

Try this!!

let obj = {
body: [
    {
      id: 0,
      data: [
        {
          cellId: 0,
          colId: 'A',
          value: '*',
        },
        {
          cellId: 1,
          colId: 'B',
          value: 'W',
        },
        {
          cellId: 2,
          colId: 'C',
          value: 'ECE',
        }
      ],
       errors: [
        {colId: 'B', errorCode: 'msg_000'},
        {colId: 'D', errorCode: 'msg_001'}
       ]
    }
]
};

let resultArr = [];

obj.body.forEach(data=>{
  let newObj = {};
  newObj['id'] = data.id;
  data.data.map(value=>{newObj[value.colId] = value.value});
  newObj['errors'] = data.errors;
  resultArr.push(newObj)
});

console.log(resultArr)
Sudhakar
  • 533
  • 1
  • 3
  • 17