【问题标题】:Filtering null values from API从 API 过滤空值
【发布时间】:2020-05-12 00:54:49
【问题描述】:

我使用 nodejs 构建了一个后端服务器 API,并将其链接到我拥有的现有数据库(其中充满了空值),然后将后端服务器链接到我的前端 react 本机项目以在我的屏幕上显示数据 所以我试图过滤掉空值,所以我的应用程序只显示具有值的值(标题 a 和 img 和每次摘录),正如您在下面的屏幕中看到的那样,我只得到一个或另一个,有时什么也没有。 所以我有办法使用 axios 或使用某种过滤功能来做到这一点

这是我在钩子中使用的代码: 使用Article.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);

【问题讨论】:

  • 在你构建的后端使用array.filter(item =&gt; item !== null),然后返回到你的前端?
  • 我应该在哪里使用它?
  • 我发布了答案

标签: javascript node.js reactjs react-native axios


【解决方案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
})

【讨论】:

  • 我编辑了我的帖子并添加了我的快速代码示例
  • 我用过这个app.get("/articles", async (req, res) =&gt; { try { //aritcles with null values const articles = await Article.find(); const articlesResponse = articles.filter((item) =&gt; item !== null); res.json(articlesResponse); } catch (err) { return res.status(422).send(err.message); } 我仍然得到空值
  • 您确定返回的文章包含空值吗?还是文章是一个对象,只有数据部分为空?例如。 { id: 1, value: null },那么你要检查article.value是否为null而不是article是否为null
  • 是的文章是一个对象,一些字段为空我如何过滤掉所有具有空值的字段,只留下所有字段中唯一具有值的字段这是一个示例:@987654331 @
  • 所以你想用什么条件过滤掉文章对象?当img 为空?,或者当有任何键为空值时?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 2021-12-06
  • 2015-07-10
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多