skip to Main Content

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


  1. 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);
    Login or Signup to reply.
  2. The simplest way is using the map method

    const duration = {
      'metrics': parent_obj.metrics.map(metric => [metric[0], metric[1]])
    };
    
    const error_ratio = {
      'metrics': parent_obj.metrics.map(metric => [metric[0], metric[2]])
    };
    
    Login or Signup to reply.
  3. You could take an helper array dor the groups and indices and map.

    const
        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]],
        indices = [[0, 1], [0, 2]];
        duration = {},
        error_ratio = {};
    
    [duration.metrics, error_ratio.metrics] = indices.map(ii => metrics.map(m => ii.map(i => m[i])));
    
    console.log(duration);
    console.log(error_ratio);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
  4. You can use the javascript built-in Array.reduce() function like the one below. I think it will work for you.

    let { duration, error_ratio } = parent_obj.metrics.reduce((data, item)=>{
        data.duration.push([item[0],item[1]])
        data.error_ratio.push([item[0],item[2]])
        return data
    },{
        duration: [],
        error_ratio: []
    })
    

    More clarification about Array.reduce() visit this link https://www.programiz.com/javascript/library/array/reduce

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search