10

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.

Impromptu_Coder
  • 425
  • 3
  • 7
  • 27
  • 1
    Supposing `other` is the other array, you can do it: `data.map(item => { return { courseid: item.courseid, name: item.name } }).forEach(item => other.push(item));` – Diullei Apr 06 '17 at 16:36

4 Answers4

22

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

const newArray = array.map(o => {
  return { name: o.name, courseid: o.courseid };
});
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
11

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"}]
Diullei
  • 11,420
  • 2
  • 27
  • 31
5

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

isuruAb
  • 2,202
  • 5
  • 26
  • 39
0

Map to a returning JSON data, subscribe it to an existing array or an empty one. #typescript

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


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


console.log(this.pictimeline);
Kofi Sammie
  • 3,237
  • 1
  • 17
  • 17