1

I'm receiving the following data in my JS from a WebService :

{
  "fire": {
    "totalOccurence": 2,
    "statsByCustomer": [
      {
        "idCustomer": 1,
        "occurence": 1
      },
      {
        "idCustomer": 2,
        "occurence": 1
      }
    ]
  },
  "flood": {
    "totalOccurence": 1,
    "statsByCustomer": [
      {
        "idCustomer": 1,
        "occurence": 1
      }
    ]
  }
}

What's the fastest way to create the following object as a result :

{
  "1": {
    "fire": 1,
    "flood": 1
  },
  "2": {
    "fire": 1,
    "flood": 0
  }
}

I'm actually doing multiple forEach to format the data myself, but i think it's pretty ugly and not efficient.. PS : the key for the result map is the customer Id

Any idea on how to do this the right way?

Thanks for your help !

3
  • I'm actually doing multiple forEach Can you please show us? Commented Feb 20, 2017 at 10:21
  • use recursive function to access to any level of data Commented Feb 20, 2017 at 10:24
  • What have you done so far? Commented Feb 20, 2017 at 10:27

1 Answer 1

2

You could iterate the outer object's keys and then the inner arrays. If an result object does not exist, create one with the wanted keys and zero values.

var data = { fire: { totalOccurence: 2, statsByCustomer: [{ idCustomer: 1, occurence: 1 }, { idCustomer: 2, occurence: 1 }] }, flood: { totalOccurence: 1, statsByCustomer: [{ idCustomer: 1, occurence: 1 }] } },
    result = {},
    keys = Object.keys(data);

keys.forEach(function (k) {
    data[k].statsByCustomer.forEach(function (a) {
        if (!result[a.idCustomer]) {
            result[a.idCustomer] = {};
            keys.forEach(function (kk) {
                result[a.idCustomer][kk] = 0;
            });
        }
        result[a.idCustomer][k] += a.occurence;
    });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

Please let OP share effort.

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.