更改嵌套对象的属性值Angular 4+

时间:2018-09-19 16:04:36

标签: angular typescript object

我正在尝试创建动态嵌套对象,但无法更改正在创建的属性的值

TS

import { Component } from '@angular/core';

  @Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
  })
  export class AppComponent {
    name = 'Test 1';
    expectedResult = {
      "0": { test: "Whoever" },
      "1": { test: "Whoever" },
      "2": { test: "Whoever" },
      "3": { test: "Whoever" },
      "4": { test: "Whoever" },
      "5": { test: "Whoever" },
      "6": { test: "Whoever" },
      "7": { test: "Whoever" },
    };
    obj = <any>{};
    test() {
      for (var i = 0; i <= 7; i++) {
        // how do i write this line 
        this.obj[i].test = "Whoever" //<-------------------------
      }
    }
  }

HTML

<hello name="{{ name }}"></hello>
<button class="btn btn-sm btn-outline-primary" (click)="test()">
Test me</button>
<pre>
  {{obj|json}}
</pre>
<pre>
  {{expectedResult|json}}
</pre>

添加stackblitz以供参考。

https://stackblitz.com/edit/mavvtogotest

编辑

谢谢大家的帮助,(对不起)也许我没有很好地解释它。该解决方案必须处理多个嵌套对象示例:

 expectedResult = {
"0": {
  "0": {
    "0": { "test": "Whoever" },
    "1": { "test": "Whoever" },
    "2": { "test": "Whoever" }
  },
  "1": {
    "0": { "test": "changeMe","notToBeChanged":"oldValue" },
    "1": { "test": "changeMe","notToBeChanged":"oldValue" },
    "2": { "test": "changeMe","notToBeChanged":"oldValue" }
  },
  "2": {
    "0": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "1": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "2": { "test": "changeMe" ,"notToBeChanged":"oldValue" }
  }
},
"1": {
  "0": {
    "0": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "1": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "2": { "test": "changeMe" ,"notToBeChanged":"oldValue" }
  },
  "1": {
    "0": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "1": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "2": { "test": "changeMe" ,"notToBeChanged":"oldValue" }
  },
  "2": {
    "0": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "1": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "2": { "test": "changeMe" ,"notToBeChanged":"oldValue" }
  }
},
"2": {
  "0": {
    "0": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "1": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "2": { "test": "changeMe" ,"notToBeChanged":"oldValue" }
  },
  "1": {
    "0": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "1": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "2": { "test": "changeMe" ,"notToBeChanged":"oldValue" }
  },
  "2": {
    "0": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "1": { "test": "changeMe" ,"notToBeChanged":"oldValue" },
    "2": { "test": "changeMe" ,"notToBeChanged":"oldValue" }
  }
}
};

3 个答案:

答案 0 :(得分:0)

如果您看到控制台,则在那里看到此错误

  

TypeError:无法设置未定义的属性“ test”

这意味着当您执行imgUrl = "http://example.com/myimage.jpg"; imgName = Path.GetFileName(imgUrl); byte[] data; using (WebClient client = new WebClient()) data = client.DownloadData(imgUrl); if (data != null) { using (MemoryStream ioStream = new MemoryStream(data)) { var path = System.IO.Path.Combine("~/Content/Images/" + imgName); var fromStream = Image.FromStream(ioStream); Image image = new Bitmap(fromStream); fromStream.Dispose(); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite)) { image.Save(ioStream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] bytes = ioStream.ToArray(); fs.Write(bytes, 0, bytes.Length); } } } 时,this.obj[i].test未定义。要解决此问题,请使用以下代码。我还让您输入this.obj[i]以便获得类型检查的好处。

obj

根据评论进行更新

如果要更新obj上的现有项目,可以使用下面的代码,因此如果那里还有其他属性,它也不会被覆盖

解决方案1 ​​

  obj : {[key:string]: {test: string}} = {};
  test() {
    for (var i = 0; i <= 7; i++) {
      // how do i write this line
      this.obj[i] = { test : "Whoever" }
    }
  }

解决方案2

  this.obj[i] = Object.assign({} ,this.obj[i], { test : "Whoever" });

答案 1 :(得分:0)

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

    constructor() { }
    obj = <any>{};
    ngOnInit() {
        this.test();
    }

    test() {
        for (let i = 0; i < 8; i++) {
            this.obj[i] = {test: 'Whoever'};
        }
        console.log(this.obj);
    }
}

答案 2 :(得分:0)

您的问题是您无法设置未定义的属性。 (有关详情,请参见控制台日志)。永远不要硬编码要迭代的长度,这不是一个好习惯。另外,不要再使用 var 。在ES6 +时代,我们使用 let const

  test() {
    let obj :  Result;
    obj = {test:'ahuevo'};
    for ( let i = 0; i <= Object.keys(this.expectedResult).length-1; i++) {
      this.objs[i] = obj;
    }
  }

我也创建了一个界面

export interface Result {
  test: string;
}

看看这个stackbliz:

https://stackblitz.com/edit/mavvtogotest-enl8f3