获取对象数组而不是对象数组

时间:2018-08-22 05:47:51

标签: javascript ecmascript-6

我有2个对象数组(this.so,模型),我试图对其进行操作以创建新的对象数组(this.soModelBOMs)。

我在两个阵列上都使用了array.filter()。map()。

但是,我得到的是对象数组而不是对象数组。

this.soModelBOMs = this.so.filter(x => x.lacking > 0).map(so => 
    model.filter(x => x.model_no == so.model_no).map(m => ({
        production_id: so.production_id,
        model_id: m.model_id,
        model_no: m.model_no,
        process_rev: m.process_rev,
        bom_rev: m.bom_rev,
        process: m.process.map(p => ({
            process_order: p.process_order,
            process_name: p.process_name,
            process_no: p.process_no,
            process_yield: p.process_yield,
            bom: p.bom.map(b => ({
                alt: b.alt,
                bom_item: b.bom_item,
                bom_name: b.bom_name,
                bom_code: b.bom_code,
                bom_qty: b.bom_qty,
                bom_stock: b.bom_stock,
                bom_yield: b.bom_yield,
                bom_req: b.bom_qty * so.lacking
            }))
        }))
    }))
)

我得到的是这样的东西:

[
  [
    {
      "production_id": 1,
      "model_id": 1,
      ...
    }
  ],
    {
      "production_id": 2,
      "model_id": 2,
      ...
    }
  [
    {
      "production_id": 3,
      "model_id": 3,
      ...
    }
  ],
]

如何修复代码,以便可以将对象推入数组中而不是将对象数组推入数组中?

类似这样的东西:

[
    {
      "production_id": 1,
      "model_id": 1,
      ...
    },
    {
      "production_id": 2,
      "model_id": 2,
      ...
    },
    {
      "production_id": 3,
      "model_id": 3,
      ...
    }
]

1 个答案:

答案 0 :(得分:1)

您可以使用find代替filter

this.soModelBOMs = this.so.filter(x => x.lacking > 0).map(so => {
var m = model.find(x => x.model_no == so.model_no);
if(m) {
    return {
        production_id: so.production_id,
        model_id: m.model_id,
        model_no: m.model_no,
        process_rev: m.process_rev,
        bom_rev: m.bom_rev,
        process: m.process.map(p => ({
            process_order: p.process_order,
            process_name: p.process_name,
            process_no: p.process_no,
            process_yield: p.process_yield,
            bom: p.bom.map(b => ({
                alt: b.alt,
                bom_item: b.bom_item,
                bom_name: b.bom_name,
                bom_code: b.bom_code,
                bom_qty: b.bom_qty,
                bom_stock: b.bom_stock,
                bom_yield: b.bom_yield,
                bom_req: b.bom_qty * so.lacking
            }))
        }))
    };
}
})

我没有测试此代码。

PS:

您可以使用spread operator将代码重构为类似

this.soModelBOMs = this.so.filter(x => x.lacking > 0).map(so => {
  var m = model.find(x => x.model_no == so.model_no);
  if (m) {
    return {
      ...so,
      ...m,
      process: m.process.map(p =>
        ({
          ...p,
          bom: p.bom.map(b =>
            ({ ...b,
              bom_req: b.bom_qty * so.lacking
            }))
        })),
    }
  }
});