オブジェクトの配列を操作する方法は知っていますが、ある配列データを別の配列に押し込む必要性はありませんでした。オブジェクトの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()やその他いくつかの関数を使用してからプッシュする必要があると読みましたが、ある配列データを別の配列にプッシュする必要があるので、私の場合はどのようにすればいいのかわかりません。
試してみてください。
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に従ってください。