繁体   English   中英

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

[英]How to push properties to an array within an object within an array via looping?

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

我的问题是我试图将每个用户条目的名称推送到数组中的特定日期,例如 26/01/2019 将具有以下名称:“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

      }

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

我期待看到数组中对象的警报。 每个对象具有不同的日期,以及每个对象中不同名称的数组。

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

您实际上可以使用键值对概念来做到这一点。 键值对的基本结构是您需要创建一个空对象。 让 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: name_array } 如果键存在,如果没有创建新的键值对,你可以执行更新。 通过这种方式,您可以避免不必要的迭代,至少据我所知,这是一种比其他方法更有效的方法

我能够执行此代码。

 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并测试

暂无
暂无

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

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