Angular 2 Array.map возвращает неопределенный - PullRequest
0 голосов
/ 25 апреля 2018

Я застрял с возвращением значения, используя Array.map в Angular 2 Так чего мне здесь не хватает?

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);
    }
}

Ответы [ 3 ]

0 голосов
/ 25 апреля 2018

Вы можете использовать findIndex () , чтобы сделать это в довольно короткие сроки:

Я не знаю точно, как выглядят ваши данные, но с учетом массива:

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

вернул бы 1 для индекса.Если индекс не найден, будет возвращено -1.

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

Надеюсь, что поможет вам.

0 голосов
/ 25 апреля 2018

Похоже, Typescript нарушает возврат. С этой модификацией я получаю желаемое значение:

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;
}
0 голосов
/ 25 апреля 2018

Я знаю, что на этот вопрос уже дан ответ, но у меня есть одно решение для этого же.

.ts код файла

 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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...