programing

개체 배열의 각도 업데이트 개체

lastmoon 2023. 8. 5. 10:54
반응형

개체 배열의 각도 업데이트 개체

예를 들어 다음과 같은 개체 배열이 있다고 가정하면 itemArray라는 이름을 붙입니다.

{
  "totalItems": 2,
  "items": [
    {
      "id": 1,
      "name": "foo"

    },
    {
      "id": 2,
      "name": "bar"
    },
    ]
}

그리고 나는 id 2의 업데이트된 결과만 반환하는 구독을 가지고 있습니다.전체 배열을 반복하지 않고 개체 배열을 업데이트하려면 어떻게 해야 합니까?

제가 원하는 것은 아래 예시와 같은 것입니다.

updateUser(user){
    this.myservice.getUpdate(user.id)
    .subscribe(newitem => {
      this.updateArray(newitem);
    });
}

  updateArray(newitem){
    this.itemArray.items[newitem.id].name = newitem.name
  }

또는 더 나은 것은 전체 개체를 교체하는 것입니다.

  updateArray(newitem){
    this.itemArray.items[newitem.id] = newitem
  }

그러나 이 예제는 배열의 인덱스를 기반으로 배열을 업데이트합니다.그렇다면 newitem.id 을 기반으로 업데이트하려면 어떻게 해야 할까요?

설명에 요청된 템플릿:

<tr *ngFor="let u of itemsArray.items; let i = index">
  <td>{{ u.id }}</td>
  <td>{{ u.name }}</td>
  <td>
    <input type="checkbox" checked="u.accepted" [(ngModel)]="itemsArray.items[i].accepted" (ngModelChange)="updateUser(u)">
    <label for="singleCheckbox-{{i}}"></label>
  </td>
</tr>

업데이트:

  showUpdatedItem(newItem){
    let indexToUpdate = this.itemArray.items.findIndex(item => item.id === newItem.id);
    this.itemArray.items[indexToUpdate] = newItem;

   // some angular libraries require breaking the array reference
   // to pick up the update in the array and trigger change detection.
   // In that case, you can do following

   this.itemArray.items = Object.assign([], this.itemArray.items);
  }

스택블리츠 데모

원본 답변:

저는 newItem.id 와 동일한 개체를 업데이트하는 당신의 예를 바탕으로 이 플런커를 만들었습니다.

다음은 제 기능의 일부입니다.

showUpdatedItem(newItem){
    let updateItem = this.itemArray.items.find(this.findIndexToUpdate, newItem.id);

    let index = this.itemArray.items.indexOf(updateItem);

    this.itemArray.items[index] = newItem;

  }

  findIndexToUpdate(newItem) { 
        return newItem.id === this;
  }

인수로 전달된 항목을 직접 업데이트하면 작업을 수행할 수 있습니다. 하지만 여기서 뭔가 누락된 것이 있을 수도 있습니다.

updateItem(item){
  this.itemService.getUpdate(item.id)
  .subscribe(updatedItem => {
    item = updatedItem;
  });
}

편집: 항목을 업데이트하기 위해 전체 배열을 반복할 수밖에 없다면 findIndex:

let itemIndex = this.items.findIndex(item => item.id == retrievedItem.id);
this.items[itemIndex] = retrievedItem;

또 다른 접근 방식은 다음과 같습니다.

let myList = [{id:'aaa1', name: 'aaa'}, {id:'bbb2', name: 'bbb'}, {id:'ccc3', name: 'ccc'}];
let itemUpdated = {id: 'aaa1', name: 'Another approach'};

myList.find(item => item.id == itemUpdated.id).name = itemUpdated.name;

기존 개체를 대체할 수도 있습니다.

toDoTaskList = [
                {id:'abcd', name:'test'},
                {id:'abcdc', name:'test'},
                {id:'abcdtr', name:'test'}
              ];

newRecordToUpdate = {id:'abcdc', name:'xyz'};
this.toDoTaskList.map((todo, i) => {
         if (todo.id == newRecordToUpdate .id){
            this.toDoTaskList[i] = updatedVal;
          }
        });

해라Array.ForEach()방법.

itemArray.ForEach(item =>{
    if(item.id == newitem.id){
        item.name = newitem.name
    }
});

나는 차라리 지도를 만들고 싶습니다.

export class item{
    name: string; 
    id: string
}

let caches = new Map<string, item>();

그런 다음 간단히 할 수 있습니다.

this.caches[newitem.id] = newitem; 

심지어.

this.caches.set(newitem.id, newitem); 

배열은 매우 1999년입니다. :)

하나의 항목을 다음과 같이 업데이트할 수 있습니다.

let item = list.find(item => item.id === id);

if( item ) {

  item.name = 'other name';

} 
updateValue(data){    
     // retriving index from array
     let indexValue = this.items.indexOf(data);
    // changing specific element in array
     this.items[indexValue].isShow =  !this.items[indexValue].isShow;
}

for 루프를 사용하여 요소를 찾고 업데이트할 수 있습니다.

updateItem(newItem){
  for (let i = 0; i < this.itemsArray.length; i++) {
      if(this.itemsArray[i].id == newItem.id){
        this.users[i] = newItem;
      }
    }
}

각도/유형 스크립트에서 배열에 있는 개체의 돌연변이를 방지할 수 있습니다.

항목 ar를 BehaviorSubject로 사용하는 예:

// you can initialize the items$ with the default array
this.items$ = new BehaviorSubject<any>([user1, user2, ...])

updateUser(user){
   this.myservice.getUpdate(user.id).subscribe(newitem => {

     // remove old item
     const items = this.items$.value.filter((item) => item.id !== newitem.id);

     // add a the newItem and broadcast a new table
     this.items$.next([...items, newItem])
   });
}

그리고 템플릿에서 아이템 $에 가입할 수 있습니다.

<tr *ngFor="let u of items$ | async; let i = index">
   <td>{{ u.id }}</td>
   <td>{{ u.name }}</td>
   <td>
        <input type="checkbox" checked="u.accepted" (click)="updateUser(u)">
        <label for="singleCheckbox-{{i}}"></label>
   </td>
</tr>

언급URL : https://stackoverflow.com/questions/44120645/angular-update-object-in-object-array

반응형