首页 > 解决方案 > 如何在 Cloud Firestore 上的地图内添加地图?

问题描述

我想像这样在firestore上添加地图对象:

在此处输入图像描述

我能够得到这个,但只是为了products[0]. 我确定我orders[0]每次都想使用,但里面所有的东西都products应该在那里。以下是我所做的:

 await FirebaseFirestore.instance.collection('orders').add({
          'dateTime': orders[0].dateTime,
          'amount': orders[0].amount,
          'products': {
            orders[0].products[0].id: {
              'title': orders[0].products[0].title,
              'quantity': orders[0].products[0].quantity,
            }
          }
        });

标签: dartgoogle-cloud-firestore

解决方案


您可以在那里使用reduce,例如:

 await FirebaseFirestore.instance.collection('orders').add({
          'dateTime': orders[0].dateTime,
          'amount': orders[0].amount,
          'products': {
            orders[0].products.reduce((acc, {id, title, quantity }) => {
             return { ...acc, { [id]: { title, quantity } } }
            }, {})
          }
        });

推荐阅读