Home > front end >  Convert objects to multidimensional array
Convert objects to multidimensional array

Time:11-18

I have an object with number of hours spent for each week:

   {
    Week 46: {
       "Other": 1
       "Planner": 4 
       "Developer": 3
    }, 
    Week 47: {
     "Planner": 4.5
     "Developer": 2
    },
    Week 48: {
     "Project Manager": 3
     "Other": 2
    }
   }

What I want to achieve is to create a multidimensional array of this, with roles as the first row and the weeks as the columns. The hour values should be filled in to the corresponding week. Sample structure below:

[["Role", "Week 46", "Week 47"],
["Planner", 4, 4.5],
["Other", 1, 0],
["Developer", 3, 2]]

The issue i am facing is that not all roles will exist in all weeks, but to get the columns correct I somehow need to fill these weeks with 0.

The reason I am converting to an md array is so I can fill it into a spreadsheet later.

I have tried below looping through the items, but I cannot wrap my head around just how the logic becomes to get the array index to the corresponding week..

function createDataFrame(data) {
    let i, j = 0;
    let arr = [['Role']];
    for (const [key, value] of Object.entries(data)) {
      arr[0].push(`Week ${key}`);
      console.log(arr);
      if (data[key]) {
        for (const [role, hours] of Object.entries(data[key])) {
          let row = [role, hours]
          arr.push(row);
        }
      }
      i  ;
    } 

CodePudding user response:

first transform your data to an object with roles as keys:

{
    "Other": {
        "Week 46": 1,
        "Week 48": 2
    },
    "Planner": {
        "Week 46": 4,
        "Week 47": 4.5
    },
    "Developer": {
        "Week 46": 3,
        "Week 47": 2
    },
    "Project Manager": {
        "Week 48": 3
    }
}

then transform to array.

function createDataFrame(data) {
    const weeks =  Object.keys(data)
    const rData = Object.entries(data).reduce((result, [week, roles]) => 
        Object.entries(roles).reduce((acc, [role, hour]) => 
            ({...acc, [role]: { ...acc[role], [week]: hour}})
        , result)
    , {})
    
    const lines = Object.entries(rData).map(([role, roleWeeks]) => {
        const line = [role, ...new Array(weeks.length).fill(0)];
        return Object.entries(roleWeeks).reduce((acc, [week, hour])=> {
            acc[weeks.indexOf(week) 1] = hour
            return acc
        }, line) 
    })
    
    return [['Roles', ...weeks], ...lines]
}

CodePudding user response:

you can use this builtin Object.entries()

  • Related