Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create nested object from list of objects

Is it possible to parse through this list and create a new nested object for every sensor after "RECORD".

{
    "TIMESTAMP": "2022-10-21 13:55:00",
    "RECORD": "0",
    "Sensor1": "1.654",
    "Sensor2": "1.176",
    "Sensor3": "0.706"
}

Result:

{
    "Sensor1": {
        "TIMESTAMP": "2022-08-21 13:55:00",
        "Value": "1.654"
    },
    "Sensor2": {
        "TIMESTAMP": "2022-08-21 13:55:00",
        "Value": "1.176"
    },
    "Sensor3": {
        "TIMESTAMP": "2022-08-21 13:55:00",
        "Value": "0.706"
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just loop through the object keys, ignore the TIMESTAMP and RECORD keys, and each other key just create its according object with the required values:

const transform = (input) => {
  return Object.keys(input).reduce((accum, inputKey) => {
    if (inputKey === 'TIMESTAMP' || inputKey === 'RECORD') {
      return accum;
    }

    return {
      ...accum,
      [inputKey]: {
        TIMESTAMP: input.TIMESTAMP,
        Value: input[inputKey]
      } 
    };
  }, {})
}

// Example
const exampleObject = {
  "TIMESTAMP": "2022-10-21 13:55:00",
  "RECORD": "0",
  "Sensor1": "1.654",
  "Sensor2": "1.176",
  "Sensor3": "0.706"
};

console.log(transform(exampleObject));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading