skip to Main Content

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

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search