You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Firebase嵌套对象返回Null:如何获取price与quantity值并展示

Fixing Null Values When Fetching Nested Firebase Objects

Hey there! Let's sort out why you're getting null when trying to pull price and quantity from your nested Firebase Realtime Database structure.

The Likely Issue

Looking at your code, you're directly trying to access price and quantity under the Orders/{listid} node. But since you mentioned these are nested sub-objects, those fields are probably stored as child items inside Orders/{listid}, not directly on that parent node itself. That's why your current code returns null—those fields don't exist at the path you're checking.

The Fix: Traverse Child Nodes

You need to loop through the child snapshots under Orders/{listid} to get the data from each nested object. Here's how to adjust your code:

var countRef = firebase.database().ref('Orders/' + listid);
countRef.on('value', snapshot => { 
  // First, check if there's any data at this path
  if (!snapshot.exists()) {
    console.log("No orders found for this list ID");
    return;
  }

  // Loop through each nested sub-object in the snapshot
  snapshot.forEach(childSnapshot => {
    const price = childSnapshot.child("price").val(); 
    const quantity = childSnapshot.child("quantity").val(); 
    
    console.log(`Price: ${price}, Quantity: ${quantity}`);

    // Add these values to your table (example implementation)
    const table = document.getElementById('your-table-id');
    const row = table.insertRow();
    row.insertCell(0).textContent = price;
    row.insertCell(1).textContent = quantity;
  });
});

Extra Debugging Tips

  • To double-check your data structure, log the full snapshot to see exactly what's stored at Orders/{listid}:
    console.log("Full data at Orders/" + listid + ":", snapshot.val());
    
  • Verify your database path matches exactly—if the nested objects are under an extra sub-node (like Orders/{listid}/items), update your ref path to match that.

Once you implement this, you'll correctly pull the price and quantity values from each nested object and be able to display them in your table.

内容的提问来源于stack exchange,提问作者Ganesh

火山引擎 最新活动