skip to Main Content

I am novice to javascript and node.js. I was able to create the following object from a json file after filtering, sorting and grouping.

{
    "2016": {
        "Delhi Daredevils": 8,
        "Gujarat Lions": 8,
        "Kings XI Punjab": 4,
        "Kolkata Knight Riders": 6,
        "Mumbai Indians": 7,
        "Rising Pune Supergiants": 4,
        "Royal Challengers Bangalore": 5,
        "Sunrisers Hyderabad": 7
    },
    "2017": {
        "Delhi Daredevils": 5,
        "Gujarat Lions": 6,
        "Kings XI Punjab": 4,
        "Kolkata Knight Riders": 9,
        "Mumbai Indians": 9,
        "Rising Pune Supergiant": 6,
        "Royal Challengers Bangalore": 5,
        "Sunrisers Hyderabad": 4
    }
}

Code used for generating this output is given below.

const csv = require("csv-parser");
const fs = require("fs");
const results = [];
let groupedResults = [];

// generic comparison function
cmp = function (x, y) {
  return x > y ? 1 : x < y ? -1 : 0;
};

//Define function with three arguments array, p1 and p2
function dataCount(array, p1, p2) {
  const group = {};

  // initialize a for loop
  for (let i = 0; i < array.length; i++) {
    //adding properties of array with _
    const batch = array[i][p1];
    const batch1 = array[i][p2];

    if (!group[batch]) {
      group[batch] = {};
      if (!group[batch][batch1]) {
        group[batch][batch1] = 1;
      } else {
        group[batch][batch1]++;
      }
    } else {
      if (!group[batch][batch1]) {
        group[batch][batch1] = 1;
      } else {
        group[batch][batch1]++;
      }
    }
  }
  //return group value
  return group;
}

fs.createReadStream("matches.csv")
  .pipe(csv())
  .on("data", (data) => {
    if (
      (data.SEASON === "2016" || data.SEASON === "2017") &&
      data.TOSS_DECISION === "field"
    ) {
      results.push(data);
    }
  })
  .on("data", () => {
    results.sort((a, b) => {
      return cmp(
        [cmp(a.TOSS_WINNER, b.TOSS_WINNER), cmp(a.SEASON, b.SEASON)],
        [cmp(b.TOSS_WINNER, a.TOSS_WINNER), cmp(b.SEASON, a.SEASON)],
      );
    });
  })
  .on("data", () => {
    groupedResults = dataCount(results, "SEASON", "TOSS_WINNER");
  })
  .on("data", () => {})
  .on("end", () => {
    fs.writeFileSync("output.txt", JSON.stringify(groupedResults), () => {
      console.log("Output successful");
    });
  });

Now I want to covert this object to the following format:

{
    "2016": {
        "0": [
            "Delhi Daredevils",
            8
        ],
        "1": [
            "Gujarat Lions",
            8
        ],
        "2": [
            "Kings XI Punjab",
            4
        ],
        "3": [
            "Kolkata Knight Riders",
            6
        ],
        "4": [
            "Mumbai Indians",
            7
        ],
        "5": [
            "Rising Pune Supergiants",
            4
        ],
        "6": [
            "Royal Challengers Bangalore",
            5
        ],
        "7": [
            "Sunrisers Hyderabad",
            7
        ]
    },
    "2017": {
        "0": [
            "Delhi Daredevils",
            5
        ],
        "1": [
            "Gujarat Lions",
            6
        ],
        "2": [
            "Kings XI Punjab",
            4
        ],
        "3": [
            "Kolkata Knight Riders",
            9
        ],
        "4": [
            "Mumbai Indians",
            9
        ],
        "5": [
            "Rising Pune Supergiant",
            6
        ],
        "6": [
            "Royal Challengers Bangalore",
            5
        ],
        "7": [
            "Sunrisers Hyderabad",
            4
        ]
    }
}

How can this be accomplished? We must use callback as this is a node.js code and will run asynchronously.

2

Answers


  1. You can loop over the object keys.

    I saved your data to data.json:

    {
      "2016": {
        "Delhi Daredevils": 8,
        "Gujarat Lions": 8,
        "Kings XI Punjab": 4,
        "Kolkata Knight Riders": 6,
        "Mumbai Indians": 7,
        "Rising Pune Supergiants": 4,
        "Royal Challengers Bangalore": 5,
        "Sunrisers Hyderabad": 7
      },
      "2017": {
        "Delhi Daredevils": 5,
        "Gujarat Lions": 6,
        "Kings XI Punjab": 4,
        "Kolkata Knight Riders": 9,
        "Mumbai Indians": 9,
        "Rising Pune Supergiant": 6,
        "Royal Challengers Bangalore": 5,
        "Sunrisers Hyderabad": 4
      }
    }
    

    Then I created a .js file:

    const data = require("./data.json");
    
    const transformData = (data) => {
      const transformedData = {};
    
      //loop over the keys
      Object.keys(data).forEach((year) => {
        transformedData[year] = {};
        const teams = Object.entries(data[year]);
    
        teams.forEach((team, index) => {
          transformedData[year][index] = team;
        });
      });
    
      return transformedData;
    };
    
    const transformedData = transformData(data);
    
    console.log(transformedData);
    

    Here, if you want to use a for loop

    const data = require("./data.json");
    
    const transformData = (data) => {
      const transformedData = {};
    
      //store the keys in a variable
      const years = Object.keys(data);
    
      //loop over the variable
      for (let i = 0; i < years.length; i++) {
        const year = years[i];
        transformedData[year] = {};
    
        const teams = Object.entries(data[year]);
    
        for (let j = 0; j < teams.length; j++) {
          const team = teams[j];
          transformedData[year][j] = team;
        }
      }
    
      return transformedData;
    };
    
    const transformedData = transformData(data);
    console.log(transformedData);
    

    Output:

    {
      '2016': {
        '0': [ 'Delhi Daredevils', 8 ],
        '1': [ 'Gujarat Lions', 8 ],
        '2': [ 'Kings XI Punjab', 4 ],
        '3': [ 'Kolkata Knight Riders', 6 ],
        '4': [ 'Mumbai Indians', 7 ],
        '5': [ 'Rising Pune Supergiants', 4 ],
        '6': [ 'Royal Challengers Bangalore', 5 ],
        '7': [ 'Sunrisers Hyderabad', 7 ]
      },
      '2017': {
        '0': [ 'Delhi Daredevils', 5 ],
        '1': [ 'Gujarat Lions', 6 ],
        '2': [ 'Kings XI Punjab', 4 ],
        '3': [ 'Kolkata Knight Riders', 9 ],
        '4': [ 'Mumbai Indians', 9 ],
        '5': [ 'Rising Pune Supergiant', 6 ],
        '6': [ 'Royal Challengers Bangalore', 5 ],
        '7': [ 'Sunrisers Hyderabad', 4 ]
      }
    }
    

    Hope this helps.

    Login or Signup to reply.
  2. You can reformat your data by reducing the object.keys and then convert the deeper to an object by spreading the result of Object.entries

    const data = {
        "2016": {"Delhi Daredevils": 8, "Gujarat Lions": 8, "Kings XI Punjab": 4, "Kolkata Knight Riders": 6, "Mumbai Indians": 7, "Rising Pune Supergiants": 4, "Royal Challengers Bangalore": 5, "Sunrisers Hyderabad": 7 },
        "2017": {"Delhi Daredevils": 5, "Gujarat Lions": 6, "Kings XI Punjab": 4, "Kolkata Knight Riders": 9, "Mumbai Indians": 9, "Rising Pune Supergiant": 6, "Royal Challengers Bangalore": 5, "Sunrisers Hyderabad": 4 }
    };
    
    const res = Object.keys(data).reduce((acc, year) => {
        acc[year] = { ...Object.entries(data[year]) }
        return acc;
    }, {});
      
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search