简体   繁体   中英

How to create dynamic colspan table in javascript react

How to generate dynamic colspan table from json data in javascript react. In obj,

w1,w2 represents the groupheader, t1,t2 represents header

for each item, display the data according to time which is grouped by week, any libraries or any possible way to create, I really got stuck.

var obj =  {
  options: {
    w1: {start:"sep",end: "6"},
    w2: {start:"nov", end: "5"}
  },
  intervals: {
    t1: {begin: "1", end: "2", totalqty: 2,totalamt: 200},
    t2: {begin: "4", end: "7", totalqty: 3, totalamt: 300},
  }
  items: [
    {
      name: "s1",
      desc: "sample1",
      w1: {t1: {qty:0, amt: 100},t2: {qty:1, amt: 200}},
      w2: {t1: {qty:1, amt: 100},t2: {qty:2, amt: 200}}
    }
    {
      name: "s2",
      desc: "sample2",
      w1: {t1: {qty:0, amt: 100},t2: {qty:0, amt: 0}},
      w2: {t1: {qty:0, amt: 0},t2: {qty:1, amt: 200}}
    }
  ]
}

Expected Ouput在此处输入图像描述

Here's what I came up with: sandbox . It does not focus on styling, but rather on generating the rows.

I've added comments where I thought it might be necessary, I'll update my answer if there's something unclear.

Few things to note:

  • I've used array indices for key properties wherever there's an array, but that's just for demo purposes. Read more about Lists and Keys here and think of selecting appropriate ID.
  • I used Object.values to make it a bit more clear, but if you need to support IE you'll need to rewrite it to Object.keys and Array.map or something else. Check browser support .
  • I've hardcoded the colspan of the interval header to 4, but it's not a big deal making it dynamic, I think.
  • Inside ItemRow component I flattened a little bit the structure so that it's easier to use and more readable. So I've tried to strike a balance between readability and performance. If this is part of some performance-critical functionality, you might want to measure and optimize further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM