繁体   English   中英

如何在javascript中的数组内创建自定义对象?

[英]How to create custom object inside an array in javascript?

JSON:(this.schedulerForm.get("schedularList").value => 这个数组包含以下数组..)

    const result = [{
                     formula_id:1,
                     quantity1:10,
                     quantity2:20,
                     quantity3:40
                     }]

转换 JSON:(上面的 JSON 数组包含 1 个具有 3 个数量值的对象。我需要将每个对象中的数量值与相同的公式 ID 以及月份和年份分开。输出应如下所示。)

    const result = [{
                      formula_id:1,
                      year:this.year,
                      month: this.month,
                      quantity:10
                      },
                       {
                      formula_id:1,
                      year:this.year,
                      month: this.month,
                      quantity:20
                      },
                      {
                      formula_id:1,
                      year:this.year,
                      month: this.month,
                      quantity:40
                      }]

组件.ts:

 month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
  year = new Date().getFullYear();
  getDate(n){
    const date = new Date();
     return date.getMonth() + n;
  }
 save() {
    console.log(this.schedulerForm.get("schedularList").value)
 }

我认为这样的事情会帮助你:

 const data = [{ formula_id:1, quantity1:10, quantity2:20, quantity3:40 }]; const year = new Date().getFullYear(); const month = 13; const mapItem = obj => propQuantity => ({ formula_id: obj.formula_id, year, month, quantity: obj[propQuantity] }); const props = ["quantity1", "quantity2", "quantity3"]; const result = data.reduce((agg, obj) => [...agg, ...props.map(mapItem(obj))], []); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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