skip to Main Content

I have the data like the below from API.I want to format the data. can anyone will help?

  fields: [
    {
      name: "A",
      values: {
        data: [1, 2, 3, 4, 5]
      }
    },
    {
      name: "B",
      values: {
        data: [6, 7, 8, 9, 10]
      }
    }
  ]

how to get the output like this

var d = [[1,6],[2,7],[3,8],[4,9],[5,10]]

2

Answers


  1. If you have the same array index and everything is static and not dynamic except the values, you can do something like this:

    const obj = {
      fields: [
        {
          name: "A",
          values: {
            data: [1, 2, 3, 4, 5]
          }
        },
        {
          name: "B",
          values: {
            data: [6, 7, 8, 9, 10]
          }
        }
      ]
    };
    
    let out;
    
    if (obj.fields[0].values.data.length === obj.fields[1].values.data.length) {
      const [d1, d2] = [obj.fields[0].values.data, obj.fields[1].values.data];
      out = d1.map((v, i) => [v, d2[i]]);
    }
    
    console.log(out);

    Assumptions:

    1. I used obj as the object that stores the response.
    2. The structure is always fields[X].values.data.
    3. There are only two indices: fields[0].values.data and fields[1].values.data.

    Output

    [ [1, 6], [2, 7], [3, 8], [4, 9], [5, 10] ]
    
    Login or Signup to reply.
  2. If the number of fields is dynamic instead of just two: you can iterate over the length of the first field’s array in an outer loop, then iterate over each field in an inner loop to pick out the number within that field’s array at the index from the outer loop (after first verifying that the length of each number array is the same for every field):

    Code in TS Playground

    function transpose(fields) {
      const length = fields[0]?.values.data.length;
      if (typeof length !== "number") return [];
    
      const result = [];
    
      for (let i = 0; i < length; i += 1) {
        const numbers = [];
        for (const field of fields) {
          if (field.values.data.length !== length) {
            throw new Error("Inconsistent lengths");
          }
          numbers.push(field.values.data[i]);
        }
        result.push(numbers);
      }
    
      return result;
    }
    
    const fields = [
      {
        name: "A",
        values: {
          data: [1, 2, 3, 4, 5],
        },
      },
      {
        name: "B",
        values: {
          data: [6, 7, 8, 9, 10],
        },
      },
    ];
    
    const expected = [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]];
    
    const actual = transpose(fields);
    
    console.log(actual);
    console.log(JSON.stringify(actual) === JSON.stringify(expected)); // true
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search