Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create separate arrays from a parent object array

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?

like image 930
gwydion93 Avatar asked Nov 18 '25 11:11

gwydion93


1 Answers

You can define helper function that use map to get the data by index:

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],
  ],
};

const getMetrics = (data, indexes) => ({
  'metrics': data.metrics.map(entry => indexes.map(index => entry[index])),
});

const duration = getMetrics(parent_obj, [0, 1]);
const error_ratio = getMetrics(parent_obj, [0, 2]);

console.log(duration);
console.log(error_ratio);
like image 115
protob Avatar answered Nov 20 '25 00:11

protob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!