简体   繁体   中英

Angular 2 Array.map returns undefined

I'm stuck with return a value using Array.map in Angular 2 So what am I missing here?

export class TabsPage {
    @ViewChild(SuperTabs) superTabs: SuperTabs;

    public rootTab: string = 'ProductListPage';
    public categories: Array<any>;
    public collection_id: number;
    public selectedindex: any;

    private getArrayIndex(source, target) {
        source.map((element, index) => {
            if (element.attrs.collection_id === target) {
                // Returns the Value i need
                console.log('i: ', index);
                return index;
            }
        });
    }

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public shopifyClientProvider: ShopifyClientProvider,
        private superTabsCtrl: SuperTabsController,
    ) {
        this.categories = navParams.get('collections');
        this.collection_id = navParams.get('collection_id');
        this.selectedindex = this.getArrayIndex(this.categories, navParams.get('collection_id'));

        // Returns undefined
        console.log('Index ', this.selectedindex);
    }
}

I know this question is already answered but I have one solution for this same.

.ts file code

 private getArrayIndex(source, target) {
  let indx = -1;
  source.map((element, index) => {
    if (element.attrs.collection_id === target) {
      // Returns the Value i need
      console.log('i: ', index);
      indx = index;
    }
  });
  return indx;
}

You can use findIndex() to do this in pretty short order:

I don't know exactly what your data looks like, but given an array:

const target = 2;
const source = [
  {
    attrs: {
      collection_id: 1
    }
  },
  {
    attrs: {
      collection_id: 2
    }
  },
  {
    attrs: {
      collection_id: 3
    }
  },
];

const index = source.findIndex(element => element.attrs.collection_id === target);

would return 1 for the index. If the index isn't found, -1 will be returned.

Plunkr: https://plnkr.co/edit/5B0gnREzyz6IJ3W3

Hope that helps you out.

Looks like Typescript breaks the return. With this modification i get the desired Value:

private getArrayIndex(source, target) {
    let found: number;
    source.map((element, index) => {
        if (element.attrs.collection_id === target) {
            console.log('i: ', index);
            found = index;
        }
    });
    return found;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM