简体   繁体   English

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

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

I am creating a small Angular application that operates like a scheduler.我正在创建一个像调度程序一样运行的小型 Angular 应用程序。 It allows users to give a Name, Start and End dates and check a boolean checkbox via a form.它允许用户提供名称、开始和结束日期,并通过表单选中布尔复选框。

My problem is I am trying to push the names of each user entry to specific dates in the array, eg 26/01/2019 will have the following names: "James", "Mark", "Luke" etc. all on the same day, depending on user entry via the form.我的问题是我试图将每个用户条目的名称推送到数组中的特定日期,例如 26/01/2019 将具有以下名称:“James”、“Mark”、“Luke”等都在同一个天,取决于用户通过表单输入。

Within my loops, I am pushing a new object for each date within a date range, but cannot figure out a way to push the names to the string array within each date object.在我的循环中,我为日期范围内的每个日期推送一个新对象,但无法找出将名称推送到每个日期对象内的字符串数组的方法。

I have tried to push the value to the array within another push, which keeps giving me errors.我试图在另一个推送中将值推送到数组,这一直给我错误。

I notice that if I set the value of the name field within the loop to "[value]" it doesn't error for some reason, not sure why.我注意到,如果我将循环中 name 字段的值设置为“[value]”,它不会出于某种原因出错,不知道为什么。

After the loops have finished, I want to alert the resulting object array, but when I write the code to do so, I get an alert of "undefined".循环完成后,我想提醒生成的对象数组,但是当我编写代码来这样做时,我收到了“未定义”的提醒。 are the values not saving to the array?值没有保存到数组中吗?

    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

      }

Actual results are an alert of "undefined".实际结果是“未定义”的警报。

I am expecting to see an alert of objects within an array.我期待看到数组中对象的警报。 Each object having a different date, and arrays of different names within each object.每个对象具有不同的日期,以及每个对象中不同名称的数组。

The way i understood you question is that:- you want to add multiple names to the same date, and at the same time you want to add new dates.我理解你的问题的方式是:-你想在同一个日期添加多个名字,同时你想添加新的日期。

You can actually do that using key value pair concept.您实际上可以使用键值对概念来做到这一点。 Basic structure of key value pair is you need to create an empty object.键值对的基本结构是您需要创建一个空对象。 let a = {};让 a = {}; and use this object to enter the values.并使用此对象输入值。 For example: in the scenario you mentioned:例如:在你提到的场景中:

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)

If you want to print all the contents use the for loop to iterate through the DATE (key value pair).如果要打印所有内容,请使用 for 循环遍历 DATE(键值对)。

One more advantage of this method is that if you want to enter a name to an existing key you do not have to iterate through all the key value pair.这种方法的另一个优点是,如果要为现有键输入名称,则不必遍历所有键值对。

you can just use the code dateObj[date] = { name: name_array } If the key exist you can perform update if not a new key value pair is created.你可以只使用代码 dateObj[date] = { name: name_array } 如果键存在,如果没有创建新的键值对,你可以执行更新。 By this way you can avoid iterating though unnecessarily Its a more efficient way than others at-least to my knowledge通过这种方式,您可以避免不必要的迭代,至少据我所知,这是一种比其他方法更有效的方法

I was able to execute this code.我能够执行此代码。

 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);

Can you post your code i can check and what went wrong你能发布你的代码吗?我可以检查一下,出了什么问题

You can put the code in here: https://rextester.com/l/js_online_compiler and test你可以把代码放在这里: https : //rextester.com/l/js_online_compiler并测试

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

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