What could be causing me to receive an undefined output when trying to access an array stored within an object

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 am encountering an issue trying to access the property "no" as it is being returned as undefined.

Answer №1

When you execute the

console.log("vvvvvvv", newdata[0].salesOrder);
command, it outputs

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

based on this, your loop needs to be structured as shown 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],
    });
}

Example Usage

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);

Answer №2

One approach is to create an object called invoices and then apply filtering based on specific criteria:

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}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to iterate through an object with multiple parameters in Op.op sequelize?

Currently, I am in the process of setting up a search API that will be able to query for specific parameters such as id, type, originCity, destinationCity, departureDate, reason, accommodation, approvalStatus, and potentially more in the future. const opt ...

The click() function in jQuery executing only once inside a "for" loop

This is an example of my HTML code: <!DOCTYPE html> <head> <title>Chemist</title> <link href="stylesheet.css" rel="stylesheet"> </head> <body> <h2 id="money"></h2> <table border="1px ...

Struggling to integrate an audio player specifically for mp3 files and feeling quite perplexed by the process

I'm struggling with implementing an audio player for a file sharing platform, specifically only for .mp3 files. I have successfully implemented a function for images (.jpeg and others), but I am unsure how to do the same for mp3 files. function is_au ...

What is the best method for extracting string values from a JavaScript object?

I am working with JavaScript objects that look like this: {["186,2017"]} My goal is to extract and display only the values: 186, 2017 Initially, I attempted to use JSON.stringify thinking it was a JSON: console.log(JSON.stringify(data)); However, thi ...

Troubleshooting undefined results with AngularJS ng-repeat filter

My objective is to create a Letter Filter, where users can click on buttons from A to Z to filter the displayed data. When clicking on the letter 'A' button, only data starting with 'A' should be shown. However, I have encountered an i ...

AngularJS: Issue with scope not updating across several views

Having one controller and two views presents a challenge. ClustersController angular.module('app.controllers').controller('ClustersController', [ '$scope', 'ClustersService', function($scope, ClustersService) { ...

Exploring the capabilities of Express.JS for integrating with an external API

const express = require('express'); const app = express(); const path = require('path'); const api = require('./api'); app.get('/', function(req, res){ res.sendFile(path.join(__dirname + '/index.html')); ...

Is there a way to create a sequence where text fades in only after the previous text has completely faded out?

Currently, I am using JQuery to create a continuous slideshow of text values. However, after some time, multiple texts start to display simultaneously, indicating a timing issue. Even when hidden, the problem persists. My code includes 3 strings of text. ...

Stop materializecss dropdown from closing when clicking within it

As I work on my current project, I am utilizing Materialize.css which includes a dropdown with various input forms inside. The dropdown can be closed by: clicking outside of .dropdown-content clicking inside of .dropdown-content clicking on .dropdown-bu ...

Is _id necessary for nested objects in NoSQL/MongoDB?

I'm struggling to understand the significance of the _id field when dealing with a simple nested object that is not stored as a root entity in its own dedicated collection. For example, let's consider a basic value object like Money({currency: S ...

Creating an Array module in Node JS

Adding a prototype to the Array class can be done in native javascript with the following code: var myArray = Array; myArray.prototype.myMethod = function(){} var testArray = new myArray(); testArray.contains(); Now I need to achieve this using a nod ...

No data found in Node.js after receiving AngularJS POST request

I've been working on sending a straightforward POST request to my server using AngularJS. The request successfully goes through and reaches the controller on the backend, but strangely, req.data is appearing as undefined. Front End Controller: funct ...

Emphasize the URL of the current page and navigate up one level

I have a list of links in my navigation. I want the current page's link to be highlighted, as well as the parent page's link one level up. For example: All pages: /blog, blog/careers, blog/authors Page: /blog/author Highlight: /blog/author, /blo ...

What is the process of converting the timing from my stopwatch to a standard time format?

I am currently working on a stopwatch project where I log the time into an array. However, when I try to use Math.min(array) or Math.max(array), it returns NaN (not a number). The time format for the stopwatch is like 00:00:15.91 which is not recognized as ...

Creating a three-dimensional representation by projecting onto the surface of a sphere in ThreeJS

3D animation is a realm filled with numerous terms and concepts that are unfamiliar to me. I am particularly confused about the significance of "UV" in 3D rendering and the tools used for mapping pixels onto a mesh. I have an image captured by a 360-degre ...

What is the most effective approach to integrating socket.io as a submodule into the ExpressJS framework?

In my current project, I am working on developing an application using ExpressJs and following the submodule architecture recommended by tjholowaychuk. Furthermore, I also want to incorporate real-time socket interactions into the app by integrating socke ...

Group Hover by StyleX

I recently experimented with the innovative StyleX library and encountered a particular challenge. Can a group hover effect be achieved for a component solely using this library? For instance, let's assume we have the following component in Tailwind ...

Exploring the power of async/await in conjunction with loops

My JavaScript code is designed to extract content from HTML pages and perform a crawling operation. However, the issue arises with asynchronous execution due to a request function. I attempted to utilize Promises and async & await to address this probl ...

What could be causing the RTCPeerConnection icegatheringstatechange to not function properly?

I have been trying to utilize the icegatheringstatechange event handler, but it doesn't seem to be functioning properly. Is there a different method I can use to monitor changes in icegatheringstate? How can I determine when all ice candidates have be ...

Troubleshooting problem: Unable to restrict table selections - issue with Material UI table in React

I seem to be overlooking the simple solution here. Currently, I have a ternary on my table. If the length of the selected array is greater than a certain number, a table with disabled checkboxes is rendered. I also implement a different handleClick functio ...