0

I want to chunk an associative array. Every item of the given array contains information about an employee.

Given array,

// given array

var arr = {
  "00B065011K": {
    "salary": "35900",
    "date": "2020-12-01"
  },
  "00B101794N": {
    "salary": "8308",
    "date": "2020-12-01"
  },
  "00C100365N": {
    "salary": "28400",
    "date": "2020-12-01"
  },
  "00D100179N": {
    "salary": "8308",
    "date": "2020-12-01"
  },
  "00D100192N": {
    "salary": "8308",
    "date": "2020-12-01"
  },
  "00E101558N": {
    "salary": "10245",
    "date": "2020-12-01"
  },
  "00F100529N": {
    "salary": "10245",
    "date": "2020-12-01",
  },
  "00F100543N": {
    "salary": "10245",
    "date": "2020-12-01"
  },
  "00G100121N": {
    "salary": "8618",
    "date": "2020-12-01"
  },
};

I want 3 employee information per chunk and output will be,

enter image description here I have tried Split array into chunks but not getting the expected output.

adiga
  • 34,372
  • 9
  • 61
  • 83
Rakibul Islam
  • 679
  • 9
  • 18
  • 3
    That is not an array; JavaScript doesn't have an "associative array" type. What you've got is a plain object. – Pointy Dec 19 '20 at 11:30

1 Answers1

2

What you have is an object, not an array. You can use Object.keys to get the keys of your object in an array, then you can use Array.reduce on that array to chunk your object into an array of smaller objects (each with chunksize properties):

var obj = {
  "00B065011K": { "salary": "35900", "date": "2020-12-01" },
  "00B101794N": { "salary": "8308", "date": "2020-12-01" },
  "00C100365N": { "salary": "28400", "date": "2020-12-01" },
  "00D100179N": { "salary": "8308", "date": "2020-12-01" },
  "00D100192N": { "salary": "8308", "date": "2020-12-01" },
  "00E101558N": { "salary": "10245", "date": "2020-12-01" },
  "00F100529N": { "salary": "10245", "date": "2020-12-01", },
  "00F100543N": { "salary": "10245", "date": "2020-12-01" },
  "00G100121N": { "salary": "8618", "date": "2020-12-01" },
};

const chunksize = 3;

const output = Object.keys(obj).reduce((c, k, i) => {
  if (i % chunksize == 0) {
    c.push(Object.fromEntries([[k, obj[k]]]));
  } else {
    c[c.length - 1][k] = obj[k];
  }
  return c;
}, []);

console.log(output);
Nick
  • 138,499
  • 22
  • 57
  • 95