开发者问题收集

从 API 中过滤空值

2020-05-12
1700

我使用 nodejs 构建了一个后端服务器 API,并将其链接到我现有的数据库(该数据库充满了空值),然后将后端服务器链接到我的前端 React Native 项目以在我的屏幕上显示数据 所以我试图过滤掉空值,这样我的应用程序就只显示有值的值(每次都是标题、图片和摘录),正如您在下面的屏幕中看到的那样,我只得到其中一个,有时什么都没有。 所以我有一种方法可以使用 axios 或使用某种过滤函数来做到这一点

这是我在钩子中使用的代码: useArticle.js

import { useEffect, useState } from "react";
import articles from "../api/articles";
import axios from "axios";
export default () => {
  const [docs, setDocs] = useState([]);
  const [errorMessage, setErrorMessage] = useState("");
  const loadApi = async () => {
    // wait for a reponse to get back once it does with some data we asign that data to the reponse variable
    try {
      const response = await axios.get("http://192.168.1.2:3001/articles");
      //console.log(response.data);
      setDocs(response.data.data);
    } catch (err) {
      setErrorMessage("Something went wrong");
    }
  };
  // bad code
  //searchApi("pasta");
  useEffect(() => {
    loadApi();
  }, []);

  return [loadApi, docs, errorMessage];
};

这是我在 TrackCreateScreen.js 上使用的代码

import React, { useState } from "react";
import { View, Text, StyleSheet, ScrollView, FlatList } from "react-native";
import SearchBar from "../components/SearchBar";
import useResults from "../hooks/useResults";
import ResutlsList from "../components/ResultsList";
import ResutlsListVer from "../components/ResultsListVer";
import useArticles from "../hooks/useArticles";
const TrackCreateScreen = () => {
  const [loadApi, docs, errorMessage] = useArticles();
  /*
  const filterNull = (docs) => {
    return docs.filter((doc) => {
      if ((doc.title = ".")) return doc.title;
    });
  };
  console.log(filterNull(docs)); */

  return (
    <View>
      <FlatList
        data={docs}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => (
          <View style={{ backgroundColor: "#abc123", padding: 10, margin: 10 }}>
            <Text style={{ color: "#fff", fontWeight: "bold" }}>
              {item.title}
            </Text>
            <Text style={{ color: "#fff" }}>{item.excerpt}</Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    //flex: 1, // when ever we have a content that is being cut off or expanding off the screen
  },
  Text: {
    fontSize: 32,
    alignItems: "center",
  },
});
export default TrackCreateScreen;

我使用 express 作为后端服务器,我的代码如下所示:

app.get("/articles", async (req, res, next) => {
  try {
    //aritcles with null values
    const articles = await Article.find();
    const articlesResponse = articles.filter((item) => {
      let isValidObject = true; // item is an article  it has title img excerpt keys
      for (let key in item) {
        if (!item[key]) isValidObject = false;
      }
      return isValidObject;
    });
    res.json(articlesResponse);
    //res.json(articles);
  } catch (err) {
    return res.status(422).send(err.message);
  }
});

在我的 server.js 文件中,我像这样调用 articleRouter:app.use("/articles", articleRouter);

带有 NULL 值的应用程序的屏幕截图

1个回答

假设您使用 Express 框架,这里有一些快速代码供您使用:

app.get('/articles', async (req, res, next) => {
   try {
       // assume you fetch from the database which contains null values here
       const withNullList = await fetchFromDbWithNullValues;

       // filter the null values here
       const articlesResponse = withNullList.filter(item => item !== null)

       res.send(articlesResponse);
   } catch (e) {
       //handle error
   }
})

如果您想过滤掉任何带有 null 值的键的文章,您可以这样做。

// filter the article items which any of its key is null here
const articlesResponse = withNullList.filter(item => {
    let isValidObject = true
    for (let key in item) {
       if (!item[key])
          isValidObject = false;
    }
    return isValidObject
})

------ 更多更新 ------

以下是您评论中的一个示例文章列表:

[
  { 
    "_id": "5eb95a068d162448a4e6a9c2", 
    "excerpt": "The shooting of Ahmaud Arbery.", 
    "img": null, 
    "task_id": "92e563d3-82c0-4f13-b393-15d5e570dfad", 
    "title": null, 
  }, 
  { 
    "_id": "5eb95a068d162448a4e6a9c3", 
    "excerpt": null, 
    "img": null, 
    "task_id": "92e563d3-82c0-4f13-b393-15d5e570dfad", 
    "title": null, 
  }
]

假设您想过滤掉 excerpt / img / title 中的任何一个为 null 的对象:

const articlesResponse = withNullList.filter(item => {
    let isValidObject = true
    if (!item.excerpt || !item.img || !item.title) // change this line according to what you want
        isValidObject = false;
    return isValidObject // if true, means we want this object, false means filter this object
})
Andus
2020-05-13