Преобразование массива объектов в массив в Javascript

#javascript #arrays

Вопрос:

Массив трендов возвращает массив объектов, в котором находится массив статей [ статьи: [{ … }]].

Как преобразовать этот массив объектов в обычный массив и извлечь массив статей.

Массив объектов

 *Object*
articles: [{…}]
status: "ok"
totalResults: 1
[[Prototype]]: Object
 

Код для извлечения и установки обоих массивов со статьями.

  fetchNews() {
    Promise.all([
      fetch(
        'url1',
      ),
      fetch(
        'url2',
      ),
    ])
      .then(([articles, trending]) => {
        return Promise.all([articles.json(), trending.json()]);
      })
      .then(([articles, trending]) => {
        return [articles, trending];
      })
      .then(([articles, trending]) => {
    

        this.setState({
          articles: articles,
          trending: trending.articles,
          refreshing: false,
        });
      });
  }
 

Структура данных возврата Promise.all([articles.json(), trending.json()]);

 bodyUsed: false
headers: Headers
map: {x-cache-remaining: "98", server: "cloudflare", nel: "{"success_fraction":0,"report_to":"cf-nel","max_age":604800}", content-encoding: "br", content-type: "application/json; charset=utf-8", …}
[[Prototype]]: Object
ok: true
status: 200
statusText: ""
type: "default"
url: "https://newsapi.org/v2/top-headlines?q=bitcoinamp;apiKey=fb54511458d44c91af1f35ce9d5a0f93"
_bodyBlob: Blob {_data: {…}}
_bodyInit: Blob {_data: {…}}
 

Попытка загрузить массив trending.articles в компонент
и элемент карусели возвращается неопределенным.

 render() {
    return (
      <SafeAreaView style={{flex: 1}}>
        <FlatList
          // eslint-disable-next-line react-native/no-inline-styles
          style={styles.bgColor}
          data={this.state.articles}
          renderItem={({item}) => <DataItem article={item} />}
          keyExtractor={item => item.url}
          refreshing={this.state.refreshing}
          onRefresh={this.handleRefresh.bind(this)}
          ListHeaderComponent={() => (
            <View>
              <Text style={styles.text}> Trending </Text>
              <Carousel
                layout={'default'}
                data={this.state.trending}
                renderItem={({item}) => <CarouselItem article={item} />}
                sliderWidth={SLIDER_WIDTH}
                itemWidth={300}
              />
              <Text style={styles.text}> Blockchain News </Text>
            </View>
          )}
        />
      </SafeAreaView>
    );
  }
}
 

Ошибка:

 ExceptionsManager.js:180 Invariant Violation: Tried to get frame for out of range index NaN

This error is located at:
    in VirtualizedList (at FlatList.js:620)
    in FlatList (at Home.js:74)
    in RCTSafeAreaView (at SafeAreaView.js:51)
    in SafeAreaView (at Home.js:73)
    in Home (at SceneView.tsx:126)
    in StaticContainer
    in EnsureSingleNavigator (at SceneView.tsx:118)
    in SceneView (at useDescriptors.tsx:209)
    in RCTView (at View.js:34)
    in View (at Screen.tsx:61)
    in RCTView (at View.js:34)
    in View (at Background.tsx:13)
    in Background (at Screen.tsx:56)
    in Screen (at BottomTabView.tsx:129)
    in RNSScreen (at createAnimatedComponent.js:217)
    in AnimatedComponent (at createAnimatedComponent.js:278)
    in AnimatedComponentWrapper (at src/index.native.tsx:150)
    in Screen (at ScreenFallback.tsx:37)
    in MaybeScreen (at BottomTabView.tsx:122)
    in RNSScreenContainer (at src/index.native.tsx:189)
    in ScreenContainer (at ScreenFallback.tsx:28)
    in MaybeScreenContainer (at BottomTabView.tsx:93)
    in RNCSafeAreaProvider (at SafeAreaContext.tsx:76)
    in SafeAreaProvider (at SafeAreaProviderCompat.tsx:38)
    in SafeAreaProviderCompat (at BottomTabView.tsx:92)
    in BottomTabView (at createBottomTabNavigator.tsx:112)
    in Unknown (at createBottomTabNavigator.tsx:111)
    in BottomTabNavigator (at TabNavigator/index.js:12)
    in TabNavigator (at RootNavigator.js:9)
    in EnsureSingleNavigator (at BaseNavigationContainer.tsx:429)
    in BaseNavigationContainer (at NavigationContainer.tsx:132)
    in ThemeProvider (at NavigationContainer.tsx:131)
    in NavigationContainerInner (at RootNavigator.js:8)
    in RootNavigator (at App.js:18)
    in App (at renderApplication.js:47)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:107)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:134)
    in AppContainer (at renderApplication.js:40)
 

Комментарии:

1. Вы что-то ищете trending.articles ? Кроме того, ваш Object.keys не имеет смысла, как и a console.log , как единственная вещь в a .map ( map преобразуется, и вы ничего не возвращаете, поэтому trendingArray никогда не будете иметь никакого содержимого)

2. Да, я смотрю на трендовые статьи. Трендинг возвращает объект, содержащий массив статей. Мне нужен этот массив статей, чтобы вставить его в мой компонент данных, так как данные принимают только массив @crashmstr

3. Проблема решена : trending.articles ?

4. @ikhvjs, если я изменю его на trending.статьи, я получу эту ошибку «ExceptionsManager.js:Нарушение инварианта 180: Пытался получить кадр для индекса вне диапазона NaN»

5. Предложение: покажите нам структуру данных результата return Promise.all([articles.json(), trending.json()]) , а затем скажите, что вам от нее нужно.