如何在TypeScript中为数组每个对象添加属性?现有方案无效求帮助
Hey there! Let's figure out how to add a property to every object in your array—no AngularJS-specific hacks required if that's not working for you. Here are a few straightforward approaches that should get the job done:
1. 原生JavaScript: Array.prototype.map() (推荐不修改原数组的方式)
This method creates a brand new array where each object gets your new property, leaving the original array untouched (super safe for avoiding unintended side effects!).
// Example original array const originalArray = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 } ]; // Add a new property (e.g., isActive: true) to each object const updatedArray = originalArray.map(obj => { // Use the spread operator to copy the original object, then add the new property return { ...obj, isActive: true }; }); console.log(updatedArray); // Output: [{name: 'Alice', age:25, isActive:true}, {name: 'Bob', age:30, isActive:true}]
If you don't mind modifying the original array directly, you can skip the spread operator and assign the property directly inside map—but the spread approach is cleaner for most cases.
2. 原生JavaScript: Array.prototype.forEach() (modify original array)
If you want to update the existing array instead of creating a new one, forEach works perfectly:
originalArray.forEach(obj => { // Assign the new property directly to each object in the array obj.isActive = true; }); console.log(originalArray); // Original array now has the new property
3. For Angular (not AngularJS) users
If you're actually working with modern Angular (TypeScript) instead of AngularJS, here's how you'd do it in a component:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-user-list', templateUrl: './user-list.component.html' }) export class UserListComponent implements OnInit { users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 } ]; ngOnInit(): void { // Update the array with map (creates new array) this.users = this.users.map(user => ({ ...user, isActive: true })); // Or use forEach to modify the original array // this.users.forEach(user => user.isActive = true); } }
Why might your AngularJS approach have failed?
A few common pitfalls to check:
- Digest cycle not triggered: If you modified the array outside of AngularJS's built-in contexts (like
$httpcallbacks orng-clickhandlers), you might need to call$scope.$apply()manually to let AngularJS detect the changes. - Immutable objects: If your objects were frozen (with
Object.freeze()) or come from a library that makes them non-extensible, you'll need to copy the object first before adding the property. - Typos or empty arrays: Double-check that your array actually contains objects (not
null/undefined) and that you spelled the property name correctly.
If you can share a snippet of the AngularJS code you tried earlier, I can help pinpoint exactly where it went wrong!
内容的提问来源于stack exchange,提问作者codedamn

