用不同的数据构造多维对象

时间:2017-03-31 11:04:53

标签: javascript object

我有三个创建三个对象的函数,firstPaymentinterimPaymentfinalPayment

firstPayment将始终拥有数据。但不应始终使用interimPaymentfinalPayment

不需要interimPaymentfinalPayment的能指基于另一个变量numberOfPayments

如果numberOfPayments === 1则只有firstPayment会有数据。如果numberOfPayments === 2则需要firstPaymentfinalPayment。最后,如果numberOfPayments > 2则需要所有三个付款对象。

我正在尝试根据paymentSchedule变量计算如何将所有这些对象添加到另一个对象numberOfPayments

这是我在代码上的开始,但我有点迷失了!

  getPaymentSchedule(id) {
    const firstPayment = this.getFirstPayment(id);
    const numberOfPayments = this.getNumberOfPayments(id);

    if (numberOfPayments === 2) {
      const finalPayment = this.getFinalPayment(id);
    } else if (numberOfPayments > 2) {
      const interimPayments = this.getInterimPayments(id);
    }
  }

这是我有点卡住的地方。我需要按顺序添加三个对象firstPaymentgetInterimPaymentsfinalPayment,但显然只有它们已经设置好。我觉得我可以比许多if语句更快地做到这一点。

我想要实现的paymentSchedule示例:

{
    firstPayment: {
        label: "foo",
        amount: 123
    },
    interimPayment: {
        label: "foo",
        amount: 123
    },
    finalPayment: {
        label: "foo",
        amount: 123
    },
}

or

{
    firstPayment: {
        label: "foo",
        amount: 123
    },
    finalPayment: {
        label: "foo",
        amount: 123
    },
}

2 个答案:

答案 0 :(得分:0)

也许我错过了一些东西,但这是你正在寻找的东西吗?

getPaymentSchedule(id) {
    const numberOfPayments = this.getNumberOfPayments(id);
    const schedule = {};
    schedule.firstPayment = this.getFirstPayment(id);

    if (numberOfPayments === 2) {
        schedule.finalPayment = this.getFinalPayment(id);
    } else if (numberOfPayments > 2) {
        schedule.interimPayments = this.getInterimPayments(id);
    }
    return schedule;
}

答案 1 :(得分:0)

您可以使用带有对象的数组。数组反映了顺序和对象。

[
    {                              // exists always
        name: 'firstPayment',
        label: 'foo',
        amount: 123            
    },
    {                              // numberOfPayments > 2
        name: 'interimPayment',
        label: 'foo',
        amount: 123            
    },
    {                              // numberOfPayments > 1
        name: 'finalPayment',
        label: 'foo',
        amount: 123            
    }
]

要生成,您可以使用类似这样的内容

var schedule = [].concat(
        this.getFirstPayment(id)
        numberOfPayments > 2 ? this.getInterimPayments(id) : [],
        numberOfPayments > 1 ? this.getFinalPayment(id) : []
    );

这将生成一个包含所需付款日期的数组。