简体   繁体   中英

How do we read one level nested deep array data from firebase in react js?

In my firebase database my data looks like below

在此处输入图像描述

my code to read data from firebase as below

export const startSetPartialExpenses = (() => {
    return (dispatch, getState) => {
        const uid = getState().auth.uid
        return database.ref(`users/${uid}/partialpayments`).once('value').then((snapshot) => {
            const partialExpenses = []
            
            snapshot.forEach((childSnapshot) => {
                
                partialExpenses.push({
                    id: childSnapshot.key,
                    ...childSnapshot.val()
                })
            })
            dispatch(setPartialExpense(partialExpenses))
        })
    }
})

after reading data from firebase, It has data like below when my component initial load在此处输入图像描述

Here I am copying data to local component object from redux store which is coming from the firebase database.

partialExpense: props.expense && props.expense.paidStatus === 'Partial Paid' ? props.partialExpense : [],

在此处输入图像描述

below I added map logic to read all the rows

<tbody className="create__partial-tbody">
{this.state.partialExpense.map((row) => (
<tr className="create__partial-tr" key={row.balance}>
<td>
  <select
    value={row.partialPaidStatus}
    onChange={(event) => this.handlepartialPaidStatusChange(row.balance, event)}
    >
    <option value="Select"> {`  `} </option>
    <option value="Partial Paid">Partial Paid</option>
    <option value="Paid">Paid</option>
  </select>
</td>
<td >
  <input 
    type="text"
    placeholder="Amount"
    value={row.partialAmount}
    onChange={(event) => this.handlepartialAmountChange(row.balance, event)}
  />
</td>

在此处输入图像描述

after adding above code, I ran my code locally machine and it is not displaying my data, it is displaying default values.

在此处输入图像描述

To get the result you are expecting will require two iterations, one for each key and one for each 'row'. Since map's only work on arrays, you need to convert it to an iterable where we can also store the key should you need to update it in the future. to preserve your structure as the context of your needs is unclear, I will map it to an array of objects.

const result = []
for (const [key, row] of Object.entries(data.val())) {
  for (const [index, value] of Object.entries(row)) {
    result.push({payKey: key, entry: index, ball: value.balance});
  }
}

from there, you should be able to manipulate the loop and code in use per your apps design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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