我知道如何操作对象数组,但从来没有必要将一个数组数据推送到另一个数组。我需要将一个对象数组推入另一个只有2个对象字段的数组中。现在我的对象格式有点像这样
data: [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
我想把它推到另一个数组中,但我只想在对象中使用courseid和name。我已经读过我们需要在构造函数中初始化对象,使用slice()和其他一些函数然后推送但是我不知道我怎么能为我做这个因为我需要将一个数组数据推送到另一个在某种程度上,有人帮助我。
答案 0 :(得分:20)
您正在寻找array map()
method:
const newArray = array.map(o => {
return { name: o.name, courseid: o.courseid };
});
答案 1 :(得分:11)
试试这个:
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"}]
答案 2 :(得分:4)
你可以这样做。
//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
进行操作答案 3 :(得分: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);