【问题标题】:How can I retrieve elements and properties from the given JSON如何从给定的 JSON 中检索元素和属性
【发布时间】:2021-06-23 15:06:03
【问题描述】:

如何访问给定 JSON 中的每个属性?

我还想根据 ID 过滤特定对象。如何在javascript中使用array.filter方法来做到这一点?

{
    "records": [
        {
            "id": "abcd",
            "fields": {
                "term": [
                    "xyz"
                ],
                "groupId": 888,
                "url": "https://www.facebook.com",
                "url_c": [
                    "https://www.google.com"
                ],
                "pID": [
                    "1800"
                ],
                "location": [
                    "mumbai"
                ],
                "url_location": [
                    "https://www.mumbai.com/"
                ]
            },
            "createdTime": "2021-05-12T10:18:33.000Z"
        }
    ]
}

目前我正在尝试这样做:

const [info, setInfo] = useState({});

  useEffect(() => {
    fetch(
      "https://apiurl//"
    )
      .then((res) => res.json())
      .then((data) => {
        setInfo(data.records);
        console.log(data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

let resultInfo = info.filter((x) => x.groupId == gid);
console.log(resultInfo[0].fields.groupId);

但它显示错误

【问题讨论】:

  • 离题:由于 fetch 是异步的,因此可能会在组件卸载后响应。在这种情况下,您需要确保不要致电setInfo。考虑使用github.com/streamich/react-use/blob/master/docs/useAsync.md,它会在后台处理所有事情。
  • 您能否提供有关此问题的更多信息,因为实际上 gid 是什么?很可能你做对了,除了一些需要改变的东西,一旦我们掌握了所有的信息就可以识别出来。谢谢

标签: javascript arrays json reactjs object


【解决方案1】:

您将info 初始化为一个空对象。因此,您的代码试图在将返回错误的对象上运行 filter。根据您共享的 json 示例,您的过滤器检查也是错误的

你应该改变

const [info, setInfo] = useState({});

let resultInfo = info.filter((x) => x.groupId == gid);

const [info, setInfo] = useState([]);

let resultInfo = info.filter((x) => x.fields.groupId == gid);

【讨论】:

    【解决方案2】:

    由于它是异步的,要么在 .then() 方法中定义东西,要么你可以简单地使用 asyn await 让事情为你工作。

    类似

    const [info, setInfo] = useState([]);
      useEffect(() => {
        fetch(
          "https://apiurl//"
        )
          .then((res) => res.json())
          .then((data) => {
        if(data && data.records){
            console.log(data);
            const records = data.records.filter((x) => x.fields.groupId == gid);
            setInfo(records);
        // if you will log info here most probably it might log default value so check in your render method for the latest value
         }
          })
          .catch((error) => {
            console.log(error);
          });
      }, []);
    
    

    确保 gid 与您的 groupId 相同。为确定起见,您可以只传递静态数字来进行测试。 现在尝试在您的渲染方法中访问信息,例如:

    return 
    <div>
    {JSON.stringify(info)}
    </div>
    
    
    

    【讨论】:

    • 这可行,但我在控制台上收到此错误:警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。
    • @Aishwariya 由于您正在调用异步函数卸载,您必须在 useEffect 的清理方法中中止该函数。您可以检查可以用来中止获取请求的各种选项,例如 React 中的 AbortController 等。为此,您可以提出另一个问题或检查解决方案。如果您的任务完成,请将其标记为答案,它将帮助其他人找到有用的答案。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 2020-09-05
    • 2021-08-11
    • 1970-01-01
    相关资源
    最近更新 更多