두 객체 어레이를 Angular 2와 TypeScript와 병합하시겠습니까?
이 주제에 대한 JavaScript 질문을 살펴보았습니다. 특히 이 질문은 TypeScript를 사용하는 Angular2에 관한 것입니다.
json 객체를 어레이에 연결하려고 합니다.
내 코드는 이렇게 생겼고
public results: [];
public getResults(){
this._service.get_search_results(this._slug, this._next).subscribe(
data => {
this.results.concat(data.results);
this._next = data.next;
},
err => {
console.log(err);
}
);
}
연결하려면 어떻게 해야 하나요?data.results
로.this.results
타자기하고 각진거?
this._slug
그리고.this._next
세팅되어 있습니다.
감사해요.
스프레드 오퍼레이터는 좀 멋있어요.
this.results = [ ...this.results, ...data.results];
확산 연산자를 사용하면 어레이의 확장 버전을 다른 어레이에 쉽게 배치할 수 있습니다.
다음 것을 사용하는 것이 좋을 것 같습니다.
data => {
this.results = this.results.concat(data.results);
this._next = data.next;
},
에서concat
문서:
concat() 메서드는 인수로서 제공된 배열 및/또는 값과 결합되어 있는 배열로 구성된 새 배열을 반환합니다.
각도 6의 확산 연산자 및 콘크리트로는 작동하지 않습니다.간단하게 해결할 수 있습니다.
result.push(...data);
ES6에서 권장하는 폼을 사용할 수도 있습니다.
data => {
this.results = [
...this.results,
data.results,
];
this._next = data.next;
},
이것은, 어레이를 최초로 초기화하는 경우에 유효합니다(public results = [];
). 그렇지 않은 경우 치환합니다....this.results,
타고...this.results ? this.results : [],
.
도움이 되었으면 좋겠다
두 개의 어레이가 있다고 가정해보세요.첫 번째는 학생 세부사항과 학생 점수 세부사항입니다.두 어레이 모두 공통 키인 'studentId'를 가지고 있습니다.
let studentDetails = [
{ studentId: 1, studentName: 'Sathish', gender: 'Male', age: 15 },
{ studentId: 2, studentName: 'kumar', gender: 'Male', age: 16 },
{ studentId: 3, studentName: 'Roja', gender: 'Female', age: 15 },
{studentId: 4, studentName: 'Nayanthara', gender: 'Female', age: 16},
];
let studentMark = [
{ studentId: 1, mark1: 80, mark2: 90, mark3: 100 },
{ studentId: 2, mark1: 80, mark2: 90, mark3: 100 },
{ studentId: 3, mark1: 80, mark2: 90, mark3: 100 },
{ studentId: 4, mark1: 80, mark2: 90, mark3: 100 },
];
키 'studentId'를 기반으로 두 어레이를 병합합니다.두 어레이를 병합하는 기능을 만들었습니다.
const mergeById = (array1, array2) =>
array1.map(itm => ({
...array2.find((item) => (item.studentId === itm.studentId) && item),
...itm
}));
최종 결과를 얻기 위한 코드입니다.
let result = mergeById(studentDetails, studentMark
);
[
{"studentId":1,"mark1":80,"mark2":90,"mark3":100,"studentName":"Sathish","gender":"Male","age":15},{"studentId":2,"mark1":80,"mark2":90,"mark3":100,"studentName":"kumar","gender":"Male","age":16},{"studentId":3,"mark1":80,"mark2":90,"mark3":100,"studentName":"Roja","gender":"Female","age":15},{"studentId":4,"mark1":80,"mark2":90,"mark3":100,"studentName":"Nayanthara","gender":"Female","age":16}
]
이거 먹어봐
data => {
this.results = [...this.results, ...data.results];
this._next = data.next;
}
언급URL : https://stackoverflow.com/questions/38092458/merge-two-object-arrays-with-angular-2-and-typescript
'programing' 카테고리의 다른 글
Facebook의 앱 내 브라우저가 "net::ERR_FAILED"이지만 다른 브라우저는 없습니다. (0) | 2023.03.18 |
---|---|
TypeError: db.collection이 함수가 아닙니다. (0) | 2023.03.18 |
JSON에 의해 시리얼화된 camel Case JSON을 반환하려면 어떻게 해야 합니까?ASP로부터의 NET.NET MVC 컨트롤러 방식 (0) | 2023.03.18 |
"jquery.unoblusive-ajax.js"는 폐지되었습니까? (0) | 2023.03.18 |
이미지 높이와 너비가 작동하지 않습니까? (0) | 2023.03.18 |