简体   繁体   English

如何在打字稿中为数组的每个对象添加属性。?

[英]How to add property to each object of an array in typescript.?

i need to add property to each object an array .我需要为每个对象添加属性数组。 i have searched a lot , got this , but this is AngularJs.我搜索了很多, 得到了这个,但这是 AngularJs。 I have tried below but not works.我在下面尝试过但没有用。 Any help appreciated任何帮助表示赞赏

 export class ThreeComponent implements OnInit {
 people = [];

 ngOnInit() { 
   this.people = [
   {'name': 'person 1', 'product': 'Medicine 1'},
   {'name': 'person 2', 'product': 'Medicine 2'},
   {'name': 'person 3', 'product': 'Medicine 3'},
   ]
  this.people.push({'total' : '2'})
  console.log(this.people)
  }
 }

results look like this:
(4) [{…}, {…}, {…}, {…}]
 0:{name: "person 1", product: "Medicine 1"}
 1:{name: "person 2", product: "Medicine 2"}
 2:{name: "person 3", product: "Medicine 3"}
 3:{total: "2"}
 length:4
 __proto__:Array(0)

expected result should be:
(3) [{…}, {…}, {…}]
 0:{name: "person 1", product: "Medicine 1", "total": "2"}
 1:{name: "person 2", product: "Medicine 2", "total": "2"}
 2:{name: "person 3", product: "Medicine 3", "total": "2"}
 length:3
 __proto__:Array(0)

NEW ANSWER新答案

You changed your question completely, you should probably make new question instead of changing whole concept.您完全改变了您的问题,您可能应该提出新问题而不是改变整个概念。 Anyway, if you have to add new properties to your data objects, there is high chance that your app is designed wrong.无论如何,如果您必须向数据对象添加新属性,则您的应用程序设计错误的可能性很高。

To add new property you don't use .push() becasue this is array method, instead you wanted to add new property to all objects.要添加新属性,您不要使用.push()因为这是数组方法,而是您想向所有对象添加新属性。 You can do this by using loop for example like this:您可以通过使用循环来做到这一点,例如:

for (var i = 0; i < this.people.length; i++) {
    this.people[i].total = 2; // Add "total": 2 to all objects in array
}

or array .map()数组 .map()

this.people.map((obj) => {
    obj.total = 2;
    // or via brackets
    // obj['total'] = 2;
    return obj;
})

Also, if you need to merge objects or add more unknown properties you can use loop or Object.assign();此外,如果您需要合并对象或添加更多未知属性,您可以使用 loop 或Object.assign();

for (var i = 0; i < this.people.length; i++) {
    // merge objects into one with multiple props
    this.people[i] = Object.assign(this.people[i], {
        total: '2', 
        someProp: 'hello', 
        likePizza: true, 
    });
}

OLD ANSWER旧答案

Ecma5 is compatabile for ES6 and looks like you probably don't know what you want to do. Ecma5 与 ES6 兼容,看起来您可能不知道自己想要做什么。

You put your code in ngOnInit so be sure you call your console.log after this event.您将代码放在ngOnInit因此请确保在此事件后调用您的console.log Your code says you called console.log(people[1].total) outside of your component class so it can't even access this property.您的代码说您在组件类之外调用了console.log(people[1].total) ,因此它甚至无法访问此属性。

Also you should not mix different types of objects in one array - this is why typescript was made, to avoid having different things in arrays and objects.此外,您不应该在一个数组中混合不同类型的对象 - 这就是制作 typescript 的原因,以避免在数组和对象中包含不同的内容。 Later in loop calling element[i].product can casue error becasue your new object has no such property.稍后在循环中调用element[i].product可能会导致错误,因为您的新对象没有这样的属性。

export class ThreeComponent implements OnInit {
  people = [];
  // people: Array<YourObjects>; // would be better

 ngOnInit() { 
   this.people = [
     {'name': 'person 1', 'product': 'Medicine 1'},
     {'name': 'person 2', 'product': 'Medicine 2'},
     {'name': 'person 3', 'product': 'Medicine 3'},
   ];
   let newLength = this.people.push({'total' : '2'}); // returns new array length
   console.log(this.people[newLength ].total); // it works in this case
 }

}

.push() returns new array length what is your new element index in this case becasue push adds new elements at the end of array. .push()返回新的数组长度,在这种情况下,您的新元素索引是多少,因为push在数组末尾添加新元素。

Array.push将元素添加到数组的末尾,因此您必须通过people[people.length-1].total访问它

You have already have 3 element in people array. 人们数组中已经有3个元素。

I think you should use console.log(this.people[3].total); 我认为您应该使用console.log(this.people[3].total);

暂无
暂无

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

相关问题 如何动态地向Typescript中数组的每个对象元素添加属性? - How to add a property to each object element of an array in Typescript dynamically? 如何在 typescript (Angular) 中数组的特定索引处向 object 添加属性? - How to add a property to an object at a specific index of an array in typescript (Angular)? 如何在 TypeScript 中将具有不同值的新属性添加到 object 的数组中? - How can I add a new property with dfiferent values to an array of object, in TypeScript? 在 Typescript 对象中添加新属性 - add new property in Typescript object 打字稿angular2:如何将数组附加到数组中的每个对象? - typescript angular2: How to append an array to each object in an array? Angular - 垫选项卡组以两种方式绑定到 typescript 中的数组。 如何通过 typescript 切换到查看某个 mat-tab? - Angular - A mat tab group is two way binded to an array in the typescript. How to switch to viewing a certain mat- tab via typescript? 向数组的每个对象添加一个新属性,该属性将动态填充 - Add a new property to each object of array which will populate dynamically 本机脚本。 Angular2 +打字稿。 将子级添加到WrapLayout - Nativescript. Angular2 + Typescript. Add Child to WrapLayout 如何根据打字稿/角度数组中的属性值对 object 进行子集化? - How to subset an object based on the property values in an array in typescript/angular? 如何使用打字稿或角度在现有对象中添加对象和数组 - How to add an object and array in an existing object using typescript or angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM