【问题标题】:convert multiple objects into an array of objects将多个对象转换为对象数组
【发布时间】:2020-06-17 19:49:15
【问题描述】:

我创建了一个函数,其中我将一个对象作为参数传递,并且有多个对象逐个传递,输出是一个对象,但它作为一个单独的对象出现,这很好,因为我已经编写了以这种方式编码现在我想将对象存储到一个数组中,这样它就成为一个对象数组。并存储所有对象 这是给出单个对象示例的经过尝试的代码

const {db} = require('./constant')
const momentTz = require("moment-timezone");
const { getAuth } = require("./constant");
const officeStatus = async officeActivity => {
  let output = {};
  const maileventQuerySnapshot = await db
    .collection("MailEvents")
    .where("office", "==", officeActivity.office)
    .where("event", "==", "delivered")
    .limit(1).get();
  output["office"] = officeActivity.office;
  output["First Contact"] = officeActivity.attachment["First Contact"].value;
  output["Second Contact"] = officeActivity.attachment["Second Contact"].value;
  output["Office Creation Date"] = momentTz
    .tz(officeActivity.timestamp, officeActivity.attachment.Timezone.value)
    .format("DD MMM YYYY");
  output["Reports Sent"] = maileventQuerySnapshot.docs.length ? true:false
  const officeSubcollectionSnapshot = await db
    .collection(`Offices/${officeActivity.officeId}/Addendum`)
    .where("date","==",parseInt( momentTz(new Date()).subtract(1, "days").format("DD")))
    .where('month', '==', parseInt( momentTz(new Date()).subtract(1, 'days').format("MM"))-1)
    .where('year', '==',parseInt( momentTz(new Date()).subtract(1, "days").format("YYYY")))
     .orderBy("user").orderBy('timestamp')
    .get();
    output['Number of unique Checkin Yesterday'] =
    officeSubcollectionSnapshot.docs.length;

  const activitiesRefSnapshot = await db
    .collection("Activities")
    .where("office", "==", officeActivity.office)
    .where("template", "==", "subscription")
    .where("attachment.Template.value", "==", "check-in")
    .get();
  const phoneNumberArray = [];
  activitiesRefSnapshot.forEach(doc => {
    phoneNumberArray.push(doc.data().attachment["Phone Number"].value);
  });
  const userRecord = await Promise.all(phoneNumberArray.map(getAuth));
  output["Number of checkin Subscription Auth"] = userRecord.filter(
    doc => doc !== undefined
  ).length;
  output["Number of Checkin Subscription No Auth"] = userRecord.filter(
    doc => doc === undefined
  ).length;
  return { output};
};
module.exports = { officeStatus };

以及我查询办公室并将对象作为参数传递的另一个文件

 const {admin,db} = require('./constant');
const { officeStatus } = require("./officeStatus");
let execute = async () => {
  try {
    let office = await db.collection("Offices").where("status", "==", "PENDING").get();
    office.forEach(doc => {
      officeStatus(doc.data())
        .then(e => {
            console.log(JSON.stringify(e.output));
        })
        .catch(error => {
          console.log(error);
        });
    });
    return;
  } catch (error) {
    console.log(error);
  }
  return;
};
execute();
 admin.apps[0].delete();


I have get output in this way 
{}
{}
{}....
and I wanted the output in this way 
[{},{},{}]

【问题讨论】:

    标签: javascript arrays node.js json google-cloud-firestore


    【解决方案1】:
     const {admin,db} = require('./constant');
    const { officeStatus } = require("./officeStatus");
    let execute = async () => {
    let office = await db.collection("Offices").where("status", "==", "PENDING").get()
      const arrayofObject = await  Promise.all(office.docs.map(doc => {
          return officeStatus(doc.data())
            .then(e => {
              // console.log(JSON.stringify(e.output));
              return e.output;
            })
            .catch(error => {
              console.log(error);
            });
        }))
    console.log(arrayofObject)
      return;
    };
    execute();
     admin.apps[0].delete();
    

    【讨论】:

      【解决方案2】:

      forEach 中的承诺不正确。它不会给你预期的结果。您不应该使用它,因为它不受支持。您应该考虑使用for..ofPromise.all。在您的情况下,我建议您使用Promise.all,因为您需要数组中的结果。

      Promise.all(office.docs.map(doc => {
        return officeStatus(doc.data())
          .then(e => {
      
            return e.output;
          })
          .catch(error => {
            console.log(error);
          });
      }))
      .then(res => console.log(res));
      
      

      【讨论】:

      • 你的打印方式与我在示例中显示的方式相同
      • 这取决于你的控制台在哪里。如果你把它放在 officeStatus 的 .then 中,你会将它作为单个对象,但如果你把控制台放在 promise.all 的 .then 中,它会将它们打印为数组。
      • 我已复制您的代码,但地图无法根据您的解决方案工作
      • 您遇到的错误是什么? .then(res => console.log(res));的输出是什么
      • 它打印一个数组,但使用这种方式并不能解决我的问题,因为我必须将它转换成一个数组数组并将它们打印到一个 excel 文件中,所以你能建议我一个我可以定义的方法吗一个数组并推送它们,因此没有范围问题
      【解决方案3】:

      尝试这样做:

      // and the other file where i have queried the office and passed objects as an argument
      
       const {admin,db} = require('./constant');
      const { officeStatus } = require("./officeStatus");
      let execute = async () => {
        try {
          let office = await db.collection("Offices").where("status", "==", "PENDING").get();
      let arr = new Array();
          office.forEach(doc => {
            officeStatus(doc.data())
              .then(e => {
                  arr.push(e)
              })
              .catch(error => {
                console.log(error);
              });
          });
      console.log(arr)
          return;
        } catch (error) {
          console.log(error);
        }
        return;
      };
      execute();
       admin.apps[0].delete();
      

      我刚刚创建了一个数组,我们在执行 officeStatus 时推送 e。然后,在代码的最后,我们记录 arr ;声明的数组。

      【讨论】:

      • 当我使用它时,它控制一个空数组,当我在内部控制时,你知道它在对象被推送时控制
      猜你喜欢
      • 2020-10-04
      • 2019-02-12
      • 2020-06-15
      • 2016-03-11
      • 2023-02-06
      • 2019-07-11
      • 1970-01-01
      相关资源
      最近更新 更多