-4

I have an array of data, but I want to convert it to an object enter image description here

how to make data array into object like this?

[
{
date: "2018-01-31",
icp: "65.59",
slc: "65.83",
dc: "64.55"
},
{
date: "2018-02-28",
icp: "61.61",
slc: "62.31",
dc: "59.93"
},
{
...
}
]

please help me to solve this problem

pilchard
  • 12,414
  • 5
  • 11
  • 23
  • loop array by skipping 4 – cmgchess Mar 30 '23 at 09:57
  • 1
    [Don't post images of code](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors). Take the time to include your input, expected output, and **your attempt** as text. – pilchard Mar 30 '23 at 10:04
  • tip: for-loops don't have to use `i++`, you can also use `i = i + 4`. – CoderApprentice Mar 30 '23 at 10:07
  • related duplicates: [Split array into chunks](https://stackoverflow.com/questions/8495687/split-array-into-chunks) and [Convert every nth element of an array to an object](https://stackoverflow.com/questions/47912608/convert-every-nth-element-of-an-array-to-an-object-in-javascript) and [Create an object from an array of keys and an array of values](https://stackoverflow.com/questions/39127989/create-an-object-from-an-array-of-keys-and-an-array-of-values) and [Convert array of data into an object](https://stackoverflow.com/questions/68900611/convert-array-of-data-into-an-object-with-properties) – pilchard Mar 30 '23 at 10:15

2 Answers2

-1

Just use forEach and do some switch logic like this:

const arr = ['2018-01-31','65.59','65.83','64.55','2018-02-28','61.61','62.31','59.93'];
let newArr = [];
let obj;
arr.forEach((data, index)=>{
  switch(index % 4) {
    case 0:
      obj = {date: data};
      break;
    case 1:
      obj.icp = data;
      break;
    case 2:
      obj.slc = data;
      break;
    default:
      obj.dc = data;
      newArr.push(obj);
  }
});
console.log(newArr);
Jordy
  • 1,802
  • 2
  • 6
  • 25
-3

Try once with following code:

const arr = [
  "2018-01-31",
  "65.56",
  "65.83",
  "64.55",
  "2018-02-28",
  "61.61",
  "62.31",
  "59.93",
  "2018-03-31",
  "61.87",
  "62.85",
  "60.26",
  "2018-04-30",
  "67.43",
  "68.39",
  "65.86",
];

const result = [];
for (let i = 0; i < arr.length; i += 4) {
  const date = arr[i];
  const icp = arr[i + 1];
  const slc = arr[i + 2];
  const dc = arr[i + 3];
  result.push({ date, icp, slc, dc });
}

console.log(result);
Drashti Kheni
  • 1,065
  • 9
  • 23