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' }
  ]
}
4
  • 3
    You need to show what you have attempted already. Commented Nov 13, 2019 at 6:50
  • JSON 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. Commented Nov 13, 2019 at 6:50
  • Please visit help center, take tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output. Commented Nov 13, 2019 at 6:51
  • let { id, errors } = obj.body[0]; let data = { id, errors }; obj.body[0].data.forEach(d => data[d.colId]=d.value) Commented Nov 13, 2019 at 7:01

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.