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.
CodePudding user response:
Since your
console.log("vvvvvvv", newdata[0].salesOrder);
statement returns
{
salesOrder: [ 623d917d4c9f21730ace6256, 623da8bbeae48b2f34372a95, 623da8bbeae48b2f34372a92, 623d98964c9f21730ace642c ],
no: [ null, '0900009293', '0900009294', null ],
}
your iteration must be like as below
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],
});
}
Sample Implementation
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);
CodePudding user response:
Actually, you can make an invoices
object first, and then filter it by any condition:
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}