1

I am having trouble reformatting an Object array in Javascript. I have an array that looks like this:

[
  {
    "deviceid": 42,
    "x": "2022-03-26T00:00:18",
    "y": 17.8,
  },
  {
    "deviceid": 42,
    "x": "2022-03-26T00:01:18",
    "y": 17.8,
  },
  {
    "deviceid": 43,
    "x": "2022-03-26T00:02:18",
    "y": 17.8,
  {
    "deviceid": 43,
    "x": "2022-03-26T00:02:18",
    "y": 17.8,
  }]

I want to re-shape it so the new form will be one record per device id and all x and y values in the same row.

[
  {
    "deviceid": 42,
    "x": ["2022-03-26T00:00:18","2022-03-27T00:00:18"],
    "y": [17.8, 15.6],
  },
  {
    "deviceid": 43,
    "x": ["2022-03-26T00:01:18","2022-03-27T00:00:18"],
    "y": [17.8, 19.1],
  }]

How can I make this happen?

1
  • It's syntactically wrong, go to jshint.com. Commented Apr 4, 2022 at 10:14

1 Answer 1

4

You can use reduce() to do the reduction of your values using a JavaScript object. After the reduction get the values of the object using Object.values().

const data = [
  {
    deviceid: 42,
    x: "2022-03-26T00:00:18",
    y: 17.8,
  },
  {
    deviceid: 42,
    x: "2022-03-26T00:01:18",
    y: 15.6,
  },
  {
    deviceid: 43,
    x: "2022-03-26T00:02:18",
    y: 17.8,
  },
  {
    deviceid: 43,
    x: "2022-03-26T00:02:18",
    y: 19.1,
  },
];

const result = data.reduce((devices, device) => {
  // check if we have encountered this decive before using the deviceId
  if (!devices.hasOwnProperty(device.deviceid)) {
    // we have not: create an key-value pair using device ID as key and device info as value
    // use an array for x and y
    devices[device.deviceid] = {
      deviceId: device.deviceid,
      x: [device.x],
      y: [device.y],
    };
  } else {
    // we have seen this device before 
    // get the device value using the key (deviceId) and push new x and y values to it
    const curDev = devices[device.deviceid];
    curDev.x.push(device.x);
    curDev.y.push(device.y);
  }
  // return JS object of devices for next iteration/ result
  return devices;
}, {});

console.log(Object.values(result));

Please note: I think the input you have provided in your question contains some errors probably from copy/ pasting as the expected output contains values that are not in the input at all. I have changed values of y in the input to show you that output is actually what you expect.

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

1 Comment

Thank you very much for your answer. It works as intended. You are also right about the input errors. It was just for the example purposes and are wrong from copy / pasting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.