1

如何在javascript中将对象更改为对象数组。

如何在javascript中修改对象并获取新的对象数组

预期结果应为输入对象周 x 2 次(输出数组中的 4 个对象)

对于每个项目。在预期输出中,组键表示周列数组,应创建每个项目 desc 的数组列表,以及每周间隔 qty

function createObject(obj){
  const results = [];
  for (var itm of obj.items) {
    group: Object.values(obj.options).map((opt, index)=>opt.start+"-"+opt.end)
  }

}


var obj =  {
  options: {
    w1: {start:"Jan",end: "1"},
    w2: {start:"Feb", end: "1"}
  },
  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},t2: {qty:1}},
      w2: {t1: {qty:1},t2: {qty:2}}
    }
    {
      name: "s2",
      desc: "sample2",
      w1: {t1: {qty:0},t2: {qty:0}},
      w2: {t1: {qty:0},t2: {qty:1}}
    }
  ]
}

预期输出:

[
  {
    group:"Jan 1", // represents w1
    columns: [
      {
      col: 'desc',
      value: 'sample1' // item.desc
      },    
      {
       col: '1-2', // represents t1
       value: 0   , // represents t1.qty
      },
      {
       col: '4-7', // represents t2   
       value: 1 // represents w1.t2.qty   
      }   
    ]
  },
  {
    group:"Feb 1", // represents w2
    columns: [
      {
      col: 'desc',
      value:'sample1' 
      },
      {
      col: '1-2', // represents t1
        value:1   , // represents t1.qty
      },
      {
       col: '4-7', // represents t2
        value:2 ,// represents t2.qty
      }
   ]
  },
  {
   group:"Jan 1", 
    columns: [
      {
      col: 'desc',
       value:'sample2' 
      },    
      {
      col: '1-2', 
        value:0, 
      },
      {
       col: '4-7', 
        value:0 
      }   
    ]
  },
  {
   group:"Feb 1",
    columns: [
      {
     col: 'desc',
       value:'sample2' 
      },
      {
       col: '1-2',
        value:0   ,
      },
      {
       col: '4-7',
        value:1,
      }
   ]
  }
]
4

1 回答 1

0

请尝试以下代码。它产生预期的结果

function createObject(obj){
    return obj.items.map((item) => {
      return Object.keys(obj.options).map((optKey) => {
        const option = obj.options[optKey];
        const items = {
            'group' : `${option.start} ${option.end}`,
            'columns': [{col: 'desc', value: item.desc}]
        };
        const intervals = item[optKey];
        Object.keys(intervals).forEach((interval) => {
            items.columns.push({
                col: `${obj.intervals[interval].begin}-${obj.intervals[interval].end}`,
                value: intervals[interval].qty
            })  
        })
        return items;
      })
    });
}
于 2020-07-26T13:05:56.087 回答