简体   繁体   English

如何使用相同的链接ID从一个.json数据获取数据到另一个.json数据?

[英]How to fetch and get data from one .json data to another .json data using the same linked id?

Here I have got the two.json files named users.json and subscription.json .在这里,我得到了名为users.jsonsubscription.json的两个 .json 文件。 In JSON file users.id links to subscription.user_id .在 JSON 文件users.id链接到subscription.user_id I have view the data of subscription.json in the table.我在表中查看了subscription.json的数据。 Now I want to get the username using id of users.json linked to user_id of subscription.json现在我想使用id of users.json链接到subscription.jsonuser_id来获取username

import React, {useEffect, useState} from 'react'
import '../UserList/userlist.css'


const Suscriber = () => {
    const [search, setSearch] = useState([]);
    const [data,setData]=useState([]);
    const [order, setorder] = useState("ASC");
    
    const [users,setUsers] = useState([{}])

    useEffect(()=>{
      fetch('data/users.json').then((res)=>res.json()).then((data)=>{
        setUsers(data)
       })
       
    },[])

    const getData=()=>{
        fetch('./data/subscriptions.json'
        ,{
          headers : { 
            'Content-Type': 'application/json',
            'Accept': 'application/json'
           }
        }
        )
          .then(function(response){
            console.log(response)
            return response.json();
          })
          .then(function(myJson) {
            console.log(myJson);
            setData(myJson)
          });
      }
      
      useEffect(()=>{
        getData()
      },[])

      const sorting = (col) => {
        if (order === "ASC") {
          const sorted = [...data].sort((a,b)=>
            a[col].toString().toLocaleLowerCase() > b[col].toString().toLocaleLowerCase() ? 1 : -1
          //   ||
          // a[col].Number.toLocaleLowerCase() < b[col].Number.toLocaleLowerCase() ? 1 : -1
            );
            setData(sorted);
            setorder("DSC");
        }
        if (order === "DSC") {
          const sorted = [...data].sort((a,b)=>
          a[col].toString().toLocaleLowerCase() < b[col].toString().toLocaleLowerCase() ? 1 : -1
          
            );
            setData(sorted);
            setorder("ASC");
        }

        }
     

    return (
        <div className="main">
            <div className="search_option">
                <h1 className="table-head">Subscribed User Data List</h1>
                <div className="input-icons">
                    <i class="fa fa-search icon" aria-hidden="true"></i>
                    <input type="search" 
                    className="input-field"
                    placeholder="Search......."
                    onChange={(event) => {
                        setSearch(event.target.value);
                    }}
                    />
                </div>  
            </div>
            <table> 
                <thead>
                  <tr>
                    <th scope="col" onClick={()=>sorting("id")}>ID <i class="fas fa-sort sortings"></i></th>
                    <th scope="col" onClick={()=>sorting("user_id")}>User ID <i class="fas fa-sort sortings"></i></th>
                    <th scope="col">Username <i class="fas fa-sort sortings"></i></th>
                    <th scope="col" onClick={()=>sorting("package")}>Package <i class="fas fa-sort sortings"></i></th>
                    <th scope="col" onClick={()=>sorting("expires_on")}>Expire on <i class="fas fa-sort sortings"></i></th>
                  </tr>
                </thead>
                <tbody>
            {data.filter((val) => {
                if (search === ""){
                    return val
                }
                else if (
                val.id.toString().toLocaleLowerCase().includes(search.toString().toLocaleLowerCase()) 
                // || val.email.toLocaleLowerCase().includes(search.toLocaleLowerCase())
                // || val.user_id.toString().toLocaleLowerCase().includes(search.toLocaleLowerCase())
                || val.package.toLocaleLowerCase().includes(search.toString().toLocaleLowerCase())
                // || val.expires_on.toString().toLocaleLowerCase().includes(search.toLocaleLowerCase())       
                ){
                    return val
                }
                return false;
            }).map((val, key) => {
              const user  = users.find(uid => uid.id === val.user_id); 
              
                return  <tr key={key}>
                    <td data-label="ID">{val.id}</td>
                    <td data-label="User ID">{val.user_id}</td>
                    <td data-label="Username">{user.username}
                      {/* {
                        subscribe.map((detail, index) => {
                          return <div>{detail.username}</div>
                        })
                      } */}
                      {/* {
                        subscribe.filter(uid => uid.id === val.user_id).map(details =>(
                          <>{details.username}</>
                        ))
                      } */}
                     
                      
                      </td>
                    <td data-label="Package">{val.package}</td>
                    <td data-label="Expire on">{val.expires_on}</td>
                    
                  </tr>  
            })}
            </tbody>  
            </table>
        </div>       
    )
}


export default Suscriber

The table includes all the data in subscriptions.json now need to find and display the same user_id and username from users.json and view it on the table below.该表包括subscriptions.json中的所有数据,现在需要从users.json中查找并显示相同的user_idusername ,并在下表中查看。

在此处输入图像描述

Below are users.json data picture:下面是users.json数据图片:

在此处输入图像描述

Below are subscriptions.json data picture:下面是subscriptions.json数据图片:

在此处输入图像描述

Instead of using Filter you can use the find method.您可以使用find方法而不是使用 Filter。

.map((val, key) => {
  // Find the user 
  const user = subscribe.find(uid => uid.id === Number(val.user_id)); 

  return  <tr key={key}>
      <td data-label="ID">{val.id}</td>
      <td data-label="User ID">{val.user_id}</td>
      <td data-label="Username">{ user?.username || '-' }</td>
      <td data-label="Package">{val.package}</td>
      <td data-label="Expire on">{val.expires_on}</td>
      
    </tr>  
})}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM