I have an object which looks as below. It can have any number of Array object
each representing count of ErrorType
.
data = { "1": [ { "ErrorType": "Error-1A", "Error": "Wrong Password for 1A" }, { "ErrorType": "Error-1B", "Error": "Host not matching" } ], "2": [ { "ErrorType": "Error-2A", "Error": "Wrong User for 1A" }, { "ErrorType": "Error-2B", "Error": "connectivity issue" } ], "3": [ { "ErrorType": "Error-3A", "Error": "Wrong version" } ], "16": [ { "ErrorType": "Error-4A", "Error": "Unknown" } ] ... ... }
I want to capture all the count values and push them in an array countArray
in descending order.
countArray = [16, 3, 2, 2, 1, 1];
I want to capture the corresponding ErrorType
and push them in an array errorTypeArray
.
errorTypeArray = ['Error-4A', 'Error-3A', 'Error-2B', 'Error-2A', 'Error-1B', 'Error-1A'];
I have written the following code so far but it is not complete:
const countArray = []; const count = Object.keys(data).length; for ( let i = 0; i < count; i++) { countArray.push(data[i]); }
Answer
If you do not need to match the key to the ErrorType, then this will work:
const data = { "1": [ { "ErrorType": "Error-1A", "Error": "Wrong Password for 1A" }, { "ErrorType": "Error-1B", "Error": "Host not matching" } ], "2": [ { "ErrorType": "Error-2A", "Error": "Wrong User for 1A" }, { "ErrorType": "Error-2B", "Error": "connectivity issue" } ], "3": [ { "ErrorType": "Error-3A", "Error": "Wrong version" } ], "16": [ { "ErrorType": "Error-4A", "Error": "Unknown" } ] }; let errorArray = []; const countArray = Object.keys(data).reduce((acc, key) => { // run over the keys data[key].forEach(item => { errorArray.push(item.ErrorType); // save the errortype acc.push(key); // save the key as many times as there are items in the array }); return acc; }, []) .sort((a, b) => b - a); errorArray.reverse() console.log(countArray) console.log(errorArray)