2017-04-06 44 views
4

我知道如何操作对象数组,但从来没有必要将一个数组数据推送到另一个数组中。我需要将对象数组推到另一个只有对象的两个字段的数组中。现在我的目标格式是有点像这个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()和其他一些函数,然后推,但我不知道我该怎么做,因为我需要将一个数组数据推入另一个有人在这方面帮助我。

+0

假设'other'是另一个阵列,就可以做到这一点:'data.map(项目=> {返回{courseid:item.courseid,名称:item.name}})。的forEach( item => other.push(item));' – Diullei

回答

11

您正在寻找的array map() method

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怀疑遵循这一url

+1

非常感谢。它为我工作。 –

+0

你能告诉我如何深入复制或克隆打字稿中的数组? –

+0

@Impromptu_Coder你看到了吗? http://stackoverflow.com/questions/35504310/deep-copy-an-array-in-angular-2-typescript – IsuruAb

0

映射到返回的JSON数据,其订阅到一个现有的阵列或空单。 #typescript

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


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


console.log(this.pictimeline); 
相关问题