Home > front end >  Parsing JSON to string from an array and creating a nested object
Parsing JSON to string from an array and creating a nested object

Time:10-15

I have a nested array, looking like that:

 

{
  "id": 1,
    "QUALITY": 91.98,
    "TEMPERATURE": 20.5,
    "SENSOR_DATE": "2021-09-24T04:53:06.801Z",
    "SOURCE_ID": 1,
    "SENSOR_NAME": "TD2",
    "NEXT_OFFSET": 11931
},

I wanna change this string

  "QUALITY": 91.98,
  "TEMPERATURE": 20.5,

to this:

{
    "data": [
        {
            "TELEMATICS": {
                "QUALITY": 91.98,
                "TEMPERATURE": 20.5
            },
            "SOURCE_ID": "1",
            "SENSOR_NAME": "TD2",
            "SENSOR__DATETIME": "2021-09-24T04:53:06.801Z"
        },
    ],
    "NEXT_OFFSET": 11931
}

I have made many different attempts, but all I could get as a result of this code is:

var telematics = JSON.parse(JSON.stringify(payload, ['QUALITY', 'TEMPERATURE']));
var data = JSON.parse(JSON.stringify(payload, ['SOURCE_ID', 'SENSOR_NAME', 'SENSO$
payload = JSON.parse(JSON.stringify({TELEMATICS: telematics, data}, null, 2));
payload = JSON.stringify({data: payload}, null, 2);

As a result, I get two different objects. I can't combine them into one, with a nested TELEMATICS array:

{
                "QUALITY": 91.33,
                "TEMPERATURE": 25.7
            }
        ],
        "data": [
            {
                "SOURCE_COMPONENT_ID": 1,
                "SENSOR_NAME": "TD2",
                "SENSOR_READING_DATETIME": "2021-09-24T04:53:06.801Z"
            },

CodePudding user response:

You said you have an array - the first item shown is an object, perhaps it's an element of that array? Let's assume so, that payload is an array of such objects.

You are trying to create a "data" array inside - with one element. Is that needed? Could it ever have more than one element? Let's assume it only has one element for now.

const payload = [{
  "id": 1,
  "QUALITY": 91.98,
  "TEMPERATURE": 20.5,
  "SENSOR_DATE": "2021-09-24T04:53:06.801Z",
  "SOURCE_ID": 1,
  "SENSOR_NAME": "TD2",
  "NEXT_OFFSET": 11931
}, {
  "id": 2,
  "QUALITY": 91.98,
  "TEMPERATURE": 20.5,
  "SENSOR_DATE": "2021-09-24T04:53:06.801Z",
  "SOURCE_ID": 1,
  "SENSOR_NAME": "TD2",
  "NEXT_OFFSET": 11931
}];

const result = payload.map(({QUALITY, TEMPERATURE, NEXT_OFFSET, ...rest})=> ({
  data: [{
    ...rest,
    TELEMATICS: {
      QUALITY,
      TEMPERATURE
    }
  }],
  NEXT_OFFSET
}));

console.log(result);

  • Related