开发者问题收集

为什么访问对象内部的数组时会出现未定义的情况?

2022-03-30
139

let newdata = await tripModel.find( { tripId: ID }, {salesOrder:1, no: "$deliveryDetails.invoiceNo", _id: 0 } );

let nullInvoices = [];

console.log("vvvvvvv", newdata[0].salesOrder);
for (let i = 0; i < newdata[0].no.length; i++) {
  if (newdata[0].no[i] === null)
    nullInvoices.push({
      SO: newdata[0].salesOrder[i],
      invoice: newdata[0].no[i],
    });
}`

//error: vvvvvvv { salesOrder: [ 623d917d4c9f21730ace6256, 623da8bbeae48b2f34372a95, 623da8bbeae48b2f34372a92, 623d98964c9f21730ace642c ], no: [ null, '0900009293', '0900009294', null ] } reason TypeError: Cannot read properties of undefined (reading 'length')

I need to access "no", but it is throwing as undefined.

2个回答

由于您的

console.log("vvvvvvv", newdata[0].salesOrder); 语句返回

{
    salesOrder: [ 623d917d4c9f21730ace6256, 623da8bbeae48b2f34372a95, 623da8bbeae48b2f34372a92, 623d98964c9f21730ace642c ],
    no: [ null, '0900009293', '0900009294', null ],
}

您的迭代必须如下所示

let nullInvoices = [];

console.log("vvvvvvv", newdata[0].salesOrder);
for (let i = 0; i < newdata[0].salesOrder.no.length; i++) {
  if (newdata[0].salesOrder.no[i] === null)
    nullInvoices.push({
      SO: newdata[0].salesOrder.salesOrder[i],
      invoice: newdata[0].salesOrder.no[i],
    });
}

示例实施

const newdata = [{}];

newdata[0].salesOrder = {
  salesOrder: ['623d917d4c9f21730ace6256', '623da8bbeae48b2f34372a95', '623da8bbeae48b2f34372a92', '623d98964c9f21730ace642c'],
  no: [null, '0900009293', '0900009294', null],
}

let nullInvoices = [];

for (let i = 0; i < newdata[0].salesOrder.no.length; i++) {
  if (newdata[0].salesOrder.no[i] === null)
    nullInvoices.push({
      SO: newdata[0].salesOrder.salesOrder[i],
      invoice: newdata[0].salesOrder.no[i],
    });
}

console.log(nullInvoices);
Nitheesh
2022-03-30

实际上,您可以先创建一个 invoices 对象,然后按任意条件对其进行过滤:

const data = {salesOrder: [ '623d917d4c9f21730ace6256', '623da8bbeae48b2f34372a95', '623da8bbeae48b2f34372a92', '623d98964c9f21730ace642c'],no: [ null, '0900009293', '0900009294', null ]};

const invoices = data.salesOrder
  .map((SO, index) => ({ SO, invoice: data.no[index] }));

const nullInvoices = invoices
  .filter(({ invoice }) => invoice === null);
  
console.log(nullInvoices);
.as-console-wrapper{min-height: 100%!important; top: 0}
A1exandr Belan
2022-03-30