【问题标题】:How to push array elements into object in angular 7如何以角度 7 将数组元素推入对象
【发布时间】:2019-11-05 19:05:01
【问题描述】:

我有一些复选框,其值来自使用 ngFor 的 json。当我选择这些复选框并单击提交时,我需要以代码部分输出中提到的对象数组的形式捕获“li”标记值和选定的复选框值。在这里,我只得到数组中的“li”标签值/文本,但我没有得到如何将它与选定的复选框值(如输出格式)一起推送到对象中。这是下面的代码。

home.component.html

 <div class="col-md-3" id="leftNavBar">
      <ul *ngFor="let item of nestedjson">
        <li class="parentNav">{{item.name}}</li>
        <li class="childData">
          <ul>
            <li *ngFor="let child of item.value">{{child}}<span class="pull-right"><input type="checkbox"></span></li>
          </ul>
        </li>
      </ul>
      <div><button type="submit" (click)="getit()">submit</button></div>
    </div>

home.component.ts

  import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    import Speech from 'speak-tts';
     import { RxSpeechRecognitionService, resultList, } from '@kamiazya/ngx-speech-recognition';
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css'],

      providers: [ RxSpeechRecognitionService ]
    })
    export class HomeComponent implements OnInit { 
        data:any;
        nestedjson:any;
        message = '';
        test:any;
     constructor(private formBuilder: FormBuilder,public service: RxSpeechRecognitionService) {
         }

      ngOnInit() {
         this.nestedjson = [
        { name: "parent1", value: ["child11", "child12"] },
        { name: "parent2", value: ["child2"] },
        { name: "parent3", value: ["child3"] }
      ];
    } 

    getit(){
        const data = this.nestedjson;
        let duplicatePushArray = [];
    for(let i = 0; i < data.length ; i++){
      if(duplicatePushArray.indexOf(data[i].name) === -1) {
        duplicatePushArray.push(data[i].name);
      } else {
        console.log(`${data[i]} is already pushed into array`);
      }
    }    
    console.log('Final Array: ', duplicatePushArray)
   /*output: [{"name":"parent1","value":["child11","child12"]},{"name":"parent2","value":["child2"]},{"name":"parent3","value":["child3"]}]*/
    }

    }

【问题讨论】:

  • 是检查所有复选框后的输出吗?请分享一些场景和预期输出
  • “home.component.ts”注释代码中已经存在输出格式。选中复选框并单击仅提交后,我需要获取输出
  • 输出 - [{"name":"parent1","value":["child11","child12"]},{"name":"parent2","value":[" child2"]},{"name":"parent3","value":["child3"]}]
  • @UIAPIDEVELOPER,如果只选择了 child11,您是否期望两个值 - 来自父级 1 - {"name":"parent1","value":["child11","child12"] 或只有 child11 - {"name":"parent1","value":["child11"]
  • {"name":"parent1","value":["child11","child12"]}

标签: html angular typescript


【解决方案1】:

当复选框被选中时,您不会发生任何事情。我建议添加一个 onChange 绑定,以便您可以将所有选中的子项保存到一个数组中,当您单击提交时可以引用该数组。

home.component.html

  <li *ngFor="let child of item.value">{{child}}
    <span class="pull-right">
      <input type="checkbox" (change)="addtoChecked(child)">
    </span>
  </li>

home.component.ts

private checkedChildren = <string[]>[];
public addToChecked(child: string): void {
  if(this.checkedChildren.indexOf(child) > -1){ // you can also pass in the $event from the html to this method to determine if it was checked or not
    this.checkedChildren = this.checkedChildren.filter(c => c !== child);
  } else {
    this.checkedChildren.push(child);
  }
}

getit(): void {
  const output = <{name: string, value: string[]}[]>[];
  this.checkedChildren.forEach((child) => {
    const jsonData = this.nestedjson.find(j => j.value.indexOf(child) > -1);
    if(!jsonData) {
      // something went wrong
      return;
    }

    const existingDataIndex = output.findIndex(o => o.name == jsonData.name);
    if(existingDataIndex === -1){
      output.push({ name: jsonData.name, value: [child]});
    } else {
      output[existingDataIndex].value.push(child);
    }
  });
  console.log(output);
}

【讨论】:

  • 在将复选框选择为数组格式后,我只得到检查值,但是如何与“li”标签值结合并将其与对象数组(如输出)- [{“name”:“parent1” ,"value":["child11","child12"]},{"name":"parent2","value":["child2"]},{"name":"parent3","value":[ "child3"]}]
  • 更新了答案。这更多的是你要找的吗?如果选择了子对象,则将父对象添加到输出中
  • 根据 cmets 的问题再次更新。只有选定的子对象会与父对象一起返回
  • 谢谢一个问题假设如果我只选择'child1'它显示child1,child2都像{“name”:“parent1”,“value”:[“child11”,“child12”] } ,它应该只显示选定的孩子
  • 使用更新的答案后在这一行出现错误 output.push({ name: jsonData.name, value[child]}); “速记属性值的范围内不存在任何值,要么声明一个,要么提供初始化程序”
【解决方案2】:

要达到预期的效果,请使用以下选项,为复选框使用 reduce 和选中标志

  1. 将选中的数组添加到原始数组以跟踪选中的框

    this.nestedjson.forEach(v => v.checked = Array(v.value.length).fill(false));

  2. 根据选中的复选框更新了选中值的数组

  3. 通过仅过滤掉选中的框来使用 reduce 更新的 Final 数组

let duplicatePushArray = this.nestedjson.reduce((acc, v) => { let temp = {name: v.name, value: []}; v.checked.forEach((val, i) => { if(val){ temp.value.push(v.value[i]); } }) if(temp.value.length > 0){ acc.push(temp) } return acc }, []);

更新了以下 app.component.html 和 app.component.ts 文件以供参考

app.component.html:

<div class="col-md-3" id="leftNavBar">
      <ul *ngFor="let item of nestedjson">
        <li class="parentNav">{{item.name}}</li>
        <li class="childData">
          <ul>
            <li *ngFor="let child of item.value; let i = index">{{child}}<span class="pull-right"><input type="checkbox" (change)="item.checked[i] = !item.checked[i]"></span></li>
          </ul>
        </li>
      </ul>
      <div><button type="submit" (click)="getit()">submit</button></div>
    </div>

app.component.ts:

import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    @Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
      })
    export class AppComponent implements OnInit { 
        data:any;
        nestedjson:any;
        message = '';
        test:any;
     constructor(private formBuilder: FormBuilder) {
         }

      ngOnInit() {
         this.nestedjson = [
        { name: "parent1", value: ["child11", "child12"] },
        { name: "parent2", value: ["child2"] },
        { name: "parent3", value: ["child3"] }
      ];

      this.nestedjson.forEach(v => v.checked = Array(v.value.length).fill(false));
    } 

    getit(){
        const data = this.nestedjson;
        let duplicatePushArray = this.nestedjson.reduce((acc, v) => {
          let temp = {name: v.name, value: []};
          v.checked.forEach((val, i) => {
            if(val){
                temp.value.push(v.value[i]);
            }
          })
          if(temp.value.length > 0){
                acc.push(temp)
          }
          return acc
        }, []);

    console.log('Final Array: ', duplicatePushArray)
   /*output: [{"name":"parent1","value":["child11","child12"]},{"name":"parent2","value":["child2"]},{"name":"parent3","value":["child3"]}]*/
    }
    }

示例工作代码供参考 - https://stackblitz.com/edit/angular-b9fmyz?file=src/app/app.component.html

【讨论】:

  • 感谢您的回答,我在我的项目中实现了它的工作正常但是如果我选中并取消选中它并再次选中其他单选框(如果是 parent1),然后单击提交按钮,它在选中的值 console.log(data) 中都显示为 true ,它不像复选框那样工作。我的意思是检查状态不正确,这是修改
  • {{child}}
  • @UIAPPDEVELOPER,所以它适用于复选框并且单选按钮失败?
  • 你能帮我解决这个问题吗,我主要关心的是在提交时捕获检查的值,而不是在更改或选择时捕获,此外,当我的复选框被预先选中时,我得到的是空数组
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签