Angular2,Typescript:How to push array of objects into another array of objects with only a few fields of the object
我知道如何操作对象数组,但从来没有必要将一个数组数据推入另一个数组数据。我需要将一个对象数组推送到另一个只有2个字段的数组中。现在我的对象格式是这样的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | data: [{ "name":"Btech", "courseid":"1", "courserating": 5, "points":"100", "type":"computers" }, { "name":"BCom", "courseid":"2", "courserating": 5, "points":"100", "type":"computers" }]; |
我想把它推入另一个数组,但我只想在对象中输入courseid和name。我已经读到,我们需要在构造函数中初始化对象,使用slice()和其他一些函数,然后push,但我不知道该怎么做,因为我需要将一个数组数据推到另一个数组数据中。请有人在这方面帮助我。
您正在查找数组
1 2 3 | const newArray = array.map(o => { return { name: o.name, courseid: o.courseid }; }); |
试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 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 <div class="suo-content">[collapse title=""]<ul><li>谢谢。它起作用了。你能告诉我怎样用typescript复制或克隆一个数组吗?</li></ul>[/collapse]</div><p><center>[wp_ad_camp_1]</center></p><hr> <p> You can simply do it like this. </p> [cc]//assign your array of object to variable var youArray:Array= [{ "name":"Btech", "courseid":"1", "courserating": 5, "points":"100", "type":"computers" }, { "name":"BCom", "courseid":"2", "courserating": 5, "points":"100", "type":"computers" }]; var resultArray:Array=[] //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) |
号
如果您对此仍有疑问,请访问此网址。
映射到返回的JSON数据,订阅现有数组或空数组。#打字稿
1 2 3 4 5 6 7 8 9 | let pictimeline= []; var timeline = this.picService.fetchtimeline(this.limit) .map((data : Response) => data.json()) .subscribe(pictimeline=> this.pictimeline = pictimeline); console.log(this.pictimeline); |