객체 배열에 대해 작업하는 방법을 알고 있지만 한 배열 데이터를 다른 배열로 푸시할 필요성은 없었습니다. 객체 배열을 객체의 필드 2개만 있는 다른 배열로 푸시해야 합니다. 현재 내 객체 형식은 다음과 같습니다.
data: [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
이것을 다른 배열로 푸시하고 싶지만 객체에 코스아이디와 이름만 넣고 싶습니다. 생성자에서 객체를 초기화하고 슬라이스() 및 기타 몇 가지 함수를 사용한 다음 푸시해야한다고 읽었지만 한 배열 데이터를 다른 배열 데이터로 푸시해야하므로 어떻게 할 수 있는지 모르겠습니다.
이렇게 해보세요:
let data = [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
let other = []; // your other array...
data.map(item => {
return {
courseid: item.courseid,
name: item.name
}
}).forEach(item => other.push(item));
console.log(JSON.stringify(other))
// => [{"courseid":"1","name":"Btech"},{"courseid":"2","name":"BCom"}]
다음과 같이 간단하게 할 수 있습니다.
//assign your array of object to variable
var youArray:Array<any>= [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
var resultArray:Array<any>=[] //empty array which we are going to push our selected items, always define types
youArray.forEach(i=>{
resultArray.push(
{
"name":i.name,
"courseid":i.courseid
});
});
console.log(resultArray)
여전히 의문점이 있으시다면 이 URL을 따라주세요.