Grouping elements of an Object

Viewed 45

Currently, my object looks like this:

obj1 = {a:'1', b:'2', c:'3', d:'4'}

What I am trying to get it to look like is this:

resultsArray: [{a: '1', b: '2'}, {c: '3', d: '4'}]

I've used Object.entries(obj1) which returns:

[ ['a', '1'], ['b', '2'], ['c', '3'], ['d', '4'] ]

I'm just not sure how to combine them. Would I just iterate through it like a normal array and concact to a new array with the pairs?

const express = require("express");
const app = express();
const axios = require("axios");
const cheerio = require("cheerio");

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use(express.static("public"));

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname + "./public/index.html"));
});

axios
  .get("https://www.espn.com/mlb/scoreboard/_/date/20220407")
  .then(function (res) {
    let $ = cheerio.load(res.data);
    let teams = [];
    let teamList = $(".ScoreCell__Truncate").each(function (i, elem) {
      teams.push($(elem).text());
    });
    let scores = [];
    let gameScores = $(".ScoreboardScoreCell__Value").each(function (i, elem) {
      scores.push($(elem).text());
    });
    let onlyRuns = adjustRuns(scores);

    const gameResults = {};

    teams.forEach((element, index) => {
      if (onlyRuns[index] !== undefined) {
        gameResults[element] = parseInt(onlyRuns[index]);
      }
    });
  });

app.listen(3000, function () {
  console.log("App is listening on port 3000");
});

function adjustRuns(arr) {
  const resultsArr = [];
  for (let i = 0; i < arr.length; i += 3) {
    resultsArr.push(arr[i]);
  }
  return resultsArr;
}
1 Answers

I asked couple of times about logic and why you transform a-b-c-d to a-b and c-d. Didn't get any information, so lets assume we want just split object in to the array of object chunks. We can create function, which will accept two parameters: object and number, which will set the size of a chunk. Check inline comments:

*** Note that the object length must be divisible by the chunk size. If not, code below will just omit any remainder. But you always can add some extra code to hold this situation differently.

// Split object in to the array chunks function
const objToChunks = (obj, size) => {
  // Define result array
  const res = [];
  // Loop object, count chunks,
  // set them to tmp object and
  // push to result array
  let tobj = {};
  Object.keys(obj).map((k, i) => {
    // Add key-value to tmp object
    tobj[k] = obj[k];
    // Here we check element index
    // by dividing it on chunk size 
    if((i+1)%size == 0) {
      // We reach 0 remainder
      // Push tmp object to result array
      // and flush tmp object
      res.push(tobj);
      tobj = {};
    }
  });
  // Return new array
  return res;
}

// Object
const obj = {
  a: '1', b: '2', c: '3',
  d: '4', e: '5', f: '6'
};

// Split object in to the array of
// object chunks with 2 items
console.log(objToChunks(obj, 2));

Related