如何通过循环将属性推入数组中对象内的数组?

时间:2019-01-26 14:50:35

标签: javascript arrays node.js angular typescript

我正在创建一个像调度程序一样运行的小型Angular应用程序。 它允许用户提供名称,开始日期和结束日期,并通过表格选中布尔复选框。

我的问题是我试图将每个用户条目的名称推到数组中的特定日期,例如2019年1月26日将具有以下名称:“詹姆斯(James)”,“马克(Mark)”,“卢克(Luke)”等,所有这些都取决于用户通过表格输入的信息。

在循环中,我要为日期范围内的每个日期推送一个新对象,但无法找出一种将名称推送至每个日期对象内的字符串数组的方法。

我试图在另一次推送中将值推送到数组,这总是给我错误。

我注意到,如果我将循环内的name字段的值设置为“ [value]”,则出于某种原因(因为不知道为什么)不会出错。

循环完成后,我想警告生成的对象数组,但是当我编写代码来警告时,会收到“未定义”的警告。值不保存到数组中?

    import { Component, OnInit } from '@angular/core';
    import { NgForm } from '@angular/forms';
    import { IPreferences } from '../ipreferences';
    import { DatePipe } from '@angular/common';
    import * as moment from 'moment';

    @Component({
      selector: 'app-customer-form',
      templateUrl: './customer-form.component.html',
      styleUrls: ['./customer-form.component.css']
    })
    export class CustomerFormComponent implements OnInit {
      title = 'Preference Form';
      preferences: IPreferences;
      dateObj: { }; // to be array of Date objects containing Name sub-arrays
      nameArray: string[];
      date = new Date();
      constructor(public datepipe: DatePipe) {
        this.preferences = {
          name: '',
          dateFrom: null,
          dateTo: null,
          everyday: null
        }
      }

      getDates(startDate, endDate){
          var dates = [],
            currentDate = startDate,
            addDays = function(days) {
              var date = new Date(this.valueOf());
              date.setDate(date.getDate() + days);
              return date;
            };
        while (currentDate <= endDate) {
          dates.push(currentDate);
          currentDate = addDays.call(currentDate, 1);
        }
        return dates;
      }

        savePreferences(form): void {
        var savedName:string = this.preferences.name;
        var formatDateFrom:string = moment(this.preferences.dateFrom).format("YYYY-MM-DD");
        var formatDateTo:string = moment(this.preferences.dateTo).format("YYYY-MM-DD");
        var savedEveryday:Boolean = this.preferences.everyday;
        var savedDateFrom:Date = new Date(formatDateFrom);
        var savedDateTo:Date = new Date(formatDateTo);
        var dateRange = this.getDates(savedDateFrom, savedDateTo);

        if(!!savedEveryday){
          for(var i = Number(savedDateFrom); i <= Number(moment(savedDateFrom).format("YYYY-MM-DD") + 90); i++){ // 90 and not infinite as due to time constraints i intended to print
            // the first 90 dates regardless of scenario, so if a user selected to receive marketing info daily it would of "appeared" to be daily

            this.nameArray.push(savedName) // pushing name strings to nameArray
          }
        }

        if(!savedEveryday) {
          dateRange.forEach(date => {
            this.nameArray.push(savedName) // pushing name strings to nameArray
        })

        this.dateObj[Number(this.date)] = {
          name: this.nameArray // attempting to set name property of objects in array to nameArray strings (2d array)
          }
        }
        alert(this.nameArray.length); // attempting to test by having a pop up of the object array (Dates) with their corresponding names returned

      }

实际结果是“未定义”的警报。

我希望看到阵列中对象的警报。每个对象具有不同的日期,并且每个对象中的名称数组不同。

2 个答案:

答案 0 :(得分:0)

我理解您的问题的方式是:-您想在同一日期添加多个名称,同时又要添加新日期。

您实际上可以使用键值对概念来做到这一点。 键值对的基本结构是您需要创建一个空对象。 让a = {}; 并使用该对象输入值。 例如:在您提到的场景中:

let dateObj = {};
let name_array =[]; // this is a temporary storage for the name;
let date =  new Date(); // this the date object that you are going to use as a key
name_array.push("James");
name_array.push("Mark");
name_array.push("Luke");

/*Below is the basic declaration of the key value pair in JavaScript*/
    dateObj[date] = {
    name: name_array
    }
/*if you want to retrieve content that is associated with the key(DATE) object use*/
dateObj[date].name // this will return all the name associated with that date object(key)

如果要打印所有内容,请使用for循环遍历DATE(键值对)。

  

此方法的另一个优点是,如果要输入名称   到现有密钥,您不必遍历所有密钥   值对。

您可以只使用代码 dateObj [date] = { 名称:name_array } 如果键存在,则可以在未创建新键值对的情况下执行更新。通过这种方式,您可以避免不必要地进行迭代,这是我所不知道的其他方法所比其他人更有效的方法

答案 1 :(得分:0)

我能够执行此代码。

 let dateObj = {};
let name_array = []; // this is a temporary storage for the name;
let date =  new Date(); // this the date object that you are going to use as a key
name_array.push("James");
name_array.push("Mark");
name_array.push("Luke");
print(name_array);
/*Below is the basic declaration of the key value pair in JavaScript*/
    dateObj[date] = {
    name: name_array
    };

/*if you want to retrieve content that is associated with the key(DATE) object use*/
dateObj[date].name;
print(dateObj[date].name);

您能发布我可以检查的代码以及出了什么问题吗

您可以将代码放在这里:https://rextester.com/l/js_online_compiler并进行测试