skip to Main Content

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"
    }
}

3

Answers


  1. 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));
    Login or Signup to reply.
  2. You can try reducing it with Object.entries(...).reduce(...);. Example below:

    const input = {
        "TIMESTAMP": "2022-10-21 13:55:00",
        "RECORD": "0",
        "Sensor1": "1.654",
        "Sensor2": "1.176",
        "Sensor3": "0.706"
    };
    
    const result = Object.entries(input).reduce((res, [key, val]) => {
      if (!key.startsWith("Sensor")) return res;
      
      res[key] = {
        TIMESTAMP: input.TIMESTAMP,
        Value: val
      };
      
      return res;
    }, {});
    
    console.log(result);
    Login or Signup to reply.
  3. Use destructuring to get TIMESTAMP from the original object.

    Use Object.entries to get [key, value] pairs from the data. Then, use filter to keep only entries whose key starts with ‘Sensor’.

    Finally, map each sensor value to a new object that includes TIMESTAMP from the original object.

    let data = { "TIMESTAMP": "2022-10-21 13:55:00", "RECORD": "0", "Sensor1": "1.654", "Sensor2": "1.176", "Sensor3": "0.706" }
    
    let {TIMESTAMP} = data
    
    let result = Object.entries(data)
      .filter(([k]) => k.startsWith('Sensor'))
      .map(([,Value]) => ({ TIMESTAMP, Value }))
    
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search