【问题标题】:Angular2,Typescript:How to push array of objects into another array of objects with only a few fields of the objectAngular2,Typescript:如何将对象数组推入另一个对象数组,其中只有几个对象字段
【发布时间】:2017-09-01 19:38:42
【问题描述】:

我知道如何对对象数组进行操作,但从来没有必要将一个数组数据推送到另一个数组中。我需要将一个对象数组推入另一个只有 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() 和其他一些函数,然后推送,但我不知道我该怎么做,因为我需要将一个数组数据推送到另一个.请有人在这方面帮助我。

【问题讨论】:

  • 假设other是另一个数组,你可以这样做:data.map(item => { return { courseid: item.courseid, name: item.name } }).forEach(item => other.push(item));

标签: arrays angular object typescript ionic2


【解决方案1】:

您正在寻找array map() method

const newArray = array.map(o => {
  return { name: o.name, courseid: o.courseid };
});

【讨论】:

    【解决方案2】:

    试试这个:

    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"}]
    

    【讨论】:

    • 非常感谢。它起作用了。你能告诉我如何在 typescript 中深度复制或克隆数组吗?
    【解决方案3】:

    你可以这样做。

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

    【讨论】:

    【解决方案4】:

    映射到返回的 JSON 数据,将其订阅到现有数组或空数组。 #打字稿

      let pictimeline= []; 
        var timeline = this.picService.fetchtimeline(this.limit)
    
    
    .map((data : Response) => data.json())
        .subscribe(pictimeline=> this.pictimeline = pictimeline);
    
    
    console.log(this.pictimeline);
    

    【讨论】:

      猜你喜欢
      • 2019-10-13
      • 2020-02-08
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 2018-10-29
      • 1970-01-01
      相关资源
      最近更新 更多