1

Incoming Data

Node is an Array of Objects

{
  "db": {
    "testing new apip": { "node": [] },
    "testing new apip 5": {
      "node": [
        {
          "id": "testing new id",
          "time": 1571679839.6459858,
          "rssi": "testing new rssi"
        },
        {
          "id": "testing new id 5",
          "time": 1571679845.8376184,
          "rssi": "testing new rssi"
        },
        {
          "id": "testing new id 55",
          "time": 1571679851.4211318,
          "rssi": "testing new rssi"
        }
      ]
    },
    "testing new apip 52": {
      "node": [
        {
          "id": "testing new id 556",
          "time": 1571679859.927497,
          "rssi": "testing new rssi"
        }
      ]
    }
  }
}

I would like to know if there is a shortcut to appending to an array without using a for loop.

Basically I want to know what is the fastest way to convert

an array of objects ==> an object of arrays.

  var data2 = {
      id: [],
      time: [],
      rssi: []
    };

This is how im doing it now:

    for (i = 0; i < data.db[AP[0]].node.length; i++) {
      data2.id.push(data.db[AP[0]].node[0].id)
      data2.time.push(data.db[AP[0]].node[0].time)
      data2.rssi.push(data.db[AP[0]].node[0].rssi)
    }
3
  • Post the example data set with desired output, then only people can give you exact answer Commented Oct 22, 2019 at 2:06
  • okay one sec let me put it together Commented Oct 22, 2019 at 2:07
  • What is AP[0]? Can you please also paste the expected output? Commented Oct 22, 2019 at 2:21

1 Answer 1

2

One approach is to use reduce().

// Array of objects.
let node = [{ "id": "testing new id", "time": 1571679839.6459858, "rssi": "testing new rssi" }, { "id": "testing new id 5", "time": 1571679845.8376184, "rssi": "testing new rssi" }, { "id": "testing new id 55", "time": 1571679851.4211318, "rssi": "testing new rssi" } ];

let result = node.reduce((acc, curr) => {
  Object.entries(curr).forEach(([key, value]) => {
    acc[key] = acc[key] || [];
    acc[key].push(value);
  });
  
  return acc;
}, {});

// Object of arrays.
console.log(result);

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

Comments

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.