Suppose I have an object that looks like this
const parent_obj = {
'metrics': [
['2023-03-28 15:40:00+00:00', 1692.1, 1.0],
['2023-02-28 15:40:00+00:00', 1211.6, 0.0],
['2023-01-28 15:40:00+00:00', 763.1, 1.0]
]
};
I want to have 2 arrays that look like this:
var duration = {
'metrics': [
['2023-03-28 15:40:00+00:00', 1692.1],
['2023-02-28 15:40:00+00:00', 1211.6],
['2023-01-28 15:40:00+00:00', 763.1]
]
};
var error_ratio = {
'metrics': [
['2023-03-28 15:40:00+00:00', 1.0],
['2023-02-28 15:40:00+00:00', 0.0],
['2023-01-28 15:40:00+00:00', 1.0]
]
};
I basically want to iterate through the metrics list and get index 0 and 1 for duration and 0 and 2 for error_ratio. What is the easiest way to accomplish this goal using vanilla javascript?
4
Answers
You can define helper function that use
map
to get the data by index:The simplest way is using the
map method
You could take an helper array dor the groups and indices and map.
You can use the javascript built-in
Array.reduce()
function like the one below. I think it will work for you.More clarification about
Array.reduce()
visit this link https://www.programiz.com/javascript/library/array/reduce