在循环中生成具有属性的对象数组

时间:2017-04-25 07:54:42

标签: javascript arrays

https://jsfiddle.net/x991kcus/

我能够生成日期数组,给定开始日期和结束日期为params,但我想要的实际上是像这样的对象数组

[{date:"2017-4-01"},{{date:"2017-4-02"}}]

下面的代码给了我数组。

function generateDates(startDate, stopDate) {
  var dateArray = [];
  var currentDate = moment(startDate);
  var stopDate = moment(stopDate);
  while (currentDate <= stopDate) {
    dateArray.push(moment(currentDate).format('YYYY-MM-DD'))
    currentDate = moment(currentDate).add(1, 'days');
  }

  return dateArray;
}

4 个答案:

答案 0 :(得分:2)

您可以使用生成的日期推送对象。

dateArray.push({ date: moment(currentDate).format('YYYY-MM-DD') });
//             ^^^^^^^                                          ^ wrap in object

const start_date_of_month = moment().format("YYYY-MM-01"),
      end_date_of_month = moment().format("YYYY-MM-") + moment().daysInMonth();

function generateDates(startDate, stopDate) {
    var dateArray = [],
        currentDate = moment(startDate),
        stopDate = moment(stopDate);

    while (currentDate <= stopDate) {
        dateArray.push({ date: moment(currentDate).format('YYYY-MM-DD') });
        currentDate = moment(currentDate).add(1, 'days');
    }
    return dateArray;
}

console.log(generateDates(start_date_of_month, end_date_of_month));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

答案 1 :(得分:1)

您可以将对象推送到dateArray

function generateDates(startDate, stopDate) {
  var dateArray = [];
  var currentDate = moment(startDate);
  var stopDate = moment(stopDate);
  while (currentDate <= stopDate) {
    obj = {};
    obj.date = moment(currentDate).format('YYYY-MM-DD')};
    dateArray.push(obj)
    currentDate = moment(currentDate).add(1, 'days');
  }
  return dateArray;
}

答案 2 :(得分:0)

https://jsfiddle.net/x991kcus/4/

while (currentDate <= stopDate) {
    var dateObject = {};
    dateObject.date = moment(currentDate).format('YYYY-MM-DD');
    dateArray.push(dateObject);
    currentDate = moment(currentDate).add(1, 'days');
}

答案 3 :(得分:0)

在JavaScript中使用Object Constructor的解决方案是创建&#34;对象类型的标准方法&#34;

function dateObject(date) {
    this.date= date;
}

function generateDates(startDate, stopDate) {
  var dateArray = [];
  var currentDate = moment(startDate);
  var stopDate = moment(stopDate);
  while (currentDate <= stopDate) {
    dateArray.push(new dateObject(moment(currentDate).format('YYYY-MM-DD')))
    currentDate = moment(currentDate).add(1, 'days');
  }

  return dateArray;
}

Working Fiddle Here