2017-04-06 1 views
4

개체 배열을 조작하는 방법을 알고 있지만 하나의 배열 데이터를 다른 개체로 푸시 할 필요가 없습니다. 객체 배열을 객체의 2 개 필드만으로 다른 배열로 푸시해야합니다. 지금 내 개체 형식은 내가 다른 배열로 밀어하려면이Angular2, Typescript : 개체의 배열을 개체의 몇 가지 필드만으로 다른 배열로 푸는 방법

data: [{ 
     "name": "Btech", 
     "courseid": "1", 
     "courserating": 5, 
     "points": "100", 
     "type": "computers" 
    }, 
    { 
     "name": "BCom", 
     "courseid": "2", 
     "courserating": 5, 
     "points": "100", 
     "type": "computers" 
    }]; 

처럼 다소이다하지만 난 개체 만 courseid와 이름을합니다. 나는 우리가 생성자에서 객체를 초기화하고, slice()와 몇 가지 다른 함수를 사용하고 푸시해야한다는 것을 읽었다. 그러나 하나의 배열 데이터를 다른 것으로 밀어 넣어야하기 때문에 어떻게해야할지 모르겠다. 친절하게도 누군가이 점에서 저를 도웁니다. 당신은 array map() method 찾고있는

+0

#typescript, 당신은 그것을 할 수 있습니다 :'data.map (항목 => {반환 {courseid : item.courseid를, 이름 : item.name}}). 대해 forEach를 (item => other.push (item)); ' – Diullei

답변

11

:

const newArray = array.map(o => { 
    return { name: o.name, courseid: o.courseid }; 
}); 
+0

고마워요. 작동합니다. –

8

이 시도 :

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"}] 
+0

고마워. 잘 했어. 타입 코드로 배열을 딥 카피하거나 복제 할 수있는 방법을 말해 줄 수 있니? –

1

당신은 그것을 이렇게 할 간단하게 할 수 있습니다.

//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) 

여전히 this.please에 대한 의심이 복귀 JSON 데이터에이 url

+1

고마워요. 그것은 나를 위해 일했습니다. –

+0

타이프 스크립트로 배열을 딥 카피하거나 복제하는 방법을 알려주시겠습니까? –

+0

@Impromptu_Coder는 이것을 보았습니까? http://deackoverflow.com/questions/35504310/deep-copy-an-array-in-angular-2-typescript – IsuruAb

0

지도에 따라 기존 배열 또는 빈 하나에 가입해야합니다. 다른 배열 other``가정하면

let pictimeline= []; 
    var timeline = this.picService.fetchtimeline(this.limit) 


.map((data : Response) => data.json()) 
    .subscribe(pictimeline=> this.pictimeline = pictimeline); 


console.log(this.pictimeline);