Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2,Typescript:How to push array of objects into another array of objects with only a few fields of the object

I know how to operate on array of objects but never had the necessity to push one array data into another. I need to push an array of objects into another array with only 2 fields of the object. Right now my object format is somewhat like this

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

I want to push this into another array but I want only courseid and name in the object. I've read that we need to initialise the object in the constructor, use slice() and a few other functions and then push but I don't know how can I do it for mine since I need to push one array data into another.Kindly someone help me in this regard.

like image 906
Impromptu_Coder Avatar asked Apr 06 '17 16:04

Impromptu_Coder


3 Answers

You're looking for the array map() method:

const newArray = array.map(o => {
  return { name: o.name, courseid: o.courseid };
});
like image 61
JB Nizet Avatar answered Nov 16 '22 01:11

JB Nizet


You can simply do it like this.

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

if you still have doubts about this.please follow this url

like image 24
isuruAb Avatar answered Nov 16 '22 01:11

isuruAb


Try this:

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"}]
like image 21
Diullei Avatar answered Nov 16 '22 02:11

Diullei