【问题标题】:To get a new array with some fields of another array获取包含另一个数组的某些字段的新数组
【发布时间】:2020-01-13 02:56:18
【问题描述】:

我正在 Ionic Angular 中处理一些数组,并且我有以下代码:

this.items = [];
this.places = [{"first_name":"joe","last_name":"Jobs","description":"engineer"},
          {"first_name":"mary","last_name":"trump","description":"doctor"}];

我需要得到这个:

this.items =[{"first_name":"joe","description":"engineer"},{"first_name":"mary","description":"doctor"}];

我有这个

        this.places.forEach((item) => {
        this.items.push('{"name:"'+ 
        item.first_name+',"description":'+item.description+'}');
    }

我收到此错误消息:

无法读取未定义的属性“push”

有人可以指导我正确的方式吗?

【问题讨论】:

    标签: javascript arrays loops object


    【解决方案1】:

    您可以直接将对象推送到 items[]

    items=[]
    places = [{"first_name":"joe","last_name":"Jobs","description":"engineer"},
              {"first_name":"mary","last_name":"trump","description":"doctor"}];
    
    places.forEach((item) => {
          items.push({
            name:item.first_name,
            description:item.description
          })
    });
    
    console.log(items)

    【讨论】:

    • 看来是对的!因为forEach回调函数体内的this.items是未定义的,所以没有push方法可以调用。
    【解决方案2】:

    你可以使用map函数,像这样:

    this.places = [{"first_name":"joe","last_name":"Jobs","description":"engineer"},
              {"first_name":"mary","last_name":"trump","description":"doctor"}];
    
    // Using map function
    this.items = this.places.map(x => ({first_name: x.first_name, description: x.description}));
    
    console.log(this.items);
    console.log('========');
    
    this.items = [];
    
    // Using forEach loop
    this.places.forEach(item => {
        this.items.push({name: item.first_name, description: item.description});
    })
    
    console.log(this.items);
    console.log('========');
    
    this.items = [];
    
    // Using for loop
    for (var item of this.places) {
        this.items.push({name: item.first_name, description: item.description});
    }
    
    console.log(this.items);

    【讨论】:

      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 2021-02-23
      • 2013-05-06
      相关资源
      最近更新 更多