Utilizing the map function in Angular while disregarding any null values

I have an array of objects in my dataset.

Here's a glimpse of how it is structured:

[
 {
  "id": 1,
  "name": "john",
  "address": { "number": 42, "street": "High Street"}
 },
 {
  "id": 2,
  "name": "jane",
  "address": Null
 },
 {
  "id": 3,
  "name": "hugh",
  "address": { "number": 64, "street": "Long Street"}
 }
]

I am attempting to extract a list of all streets from the dataset by utilizing the following code:

const streets = this.dataset.map((d) => d.address && d.address.street).sort();

Nevertheless, I'm encountering a

cannot read property street of null
error due to instances where the address value is null.

Is there a method through which I can ignore null values when using the map function?

I've experimented with .filter(Boolean), but that doesn't seem to resolve the issue as the object itself isn't null.

Answer №1

Filtering based on the address attribute can be done as follows:

this.dataset.filter(data => data.address).map(data => data.address.street).sort()

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

The absence of a type annotation for `T` has been noted

Attempting to create code with a simple JavaScript function: filterArray(user: any, items: Array<Object>) { items = items.filter(item => {return true;}); return items; } Encountering the following error: Error message: Missing type anno ...

Facing issues with React JS and Material UI? If you're encountering problems where 'this.props' is

After running the code provided below, I anticipated that the styles would be injected within props. However, I consistently encounter undefined props. No props are being supplied to this component. const customStyles = theme => ({ root: { & ...

The console logs indicate success for every call, but unfortunately Twitter is not displaying the retweets

Hey there! I'm having some trouble with calling a function and it's not working as expected. var T = new Twit(config); var retweet = function() { T.get('search/tweets', {q:'#python3, #nodejs, python3, nodejs,', count :5 }, f ...

Unable to pass response from httpclient post method to another custom function in Angular 4

I've implemented the addUser(newUser) function in my sign-in.service.ts file like this: addUser(newUser) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; let body = JS ...

Tips for transferring JavaScript values to PHP through AjaxWould you like to learn how to

Let's set the scene. I'm currently facing a challenge in passing Javascript values to different PHP functions within my ajax code so that they can be properly displayed on the page. Here is the snippet of my code: $("[data-departmen ...

Top method for filling an array with strings

Imagine having an array called 'newArray'. var newArray = []; You can add strings to it like this: var thisString = 'watch'; newArray.push(thisString); Now, if you want to have 50 instances of the 'thisString' in the newAr ...

What's stopping me from using useState() to assign API data to an array?

I have a question regarding my app that makes use of the Movies API. I am making an API request and then passing the data to an array using the useState hook. Here is a snippet of my code: const App = () => { type MovieType = { rate: string, ...

Select a hyperlink to access the corresponding tab

I've been playing around with bootstrap and AngularJS. I placed nav-tabs inside a modal-window and have it open when clicking on a link. However, I want the appropriate tab to open directly upon click. For example, if I click on "travel", I want the t ...

What are some effective methods for selectively handling batches of 5-20k document inputs when adding them to a collection containing up to one million documents using MongoDB and Mongoose?

My MMO census and character stats tracking application receives input batches containing up to 5-20k documents per user, which need to be aggregated into the database. I have specific criteria to determine whether a document from the input already exists i ...

Using res.sendfile in a Node Express server and sending additional data along with the file

Can a Node.JS application redirect to an HTML file using the res.sendFile method from express and include JSON data in the process? ...

Using ASCII 3D text can create a stunning visual effect on a website, but it can sometimes appear

My website is displaying ASCII 3D Text with glitchy lines, but this issue is not present on other websites. Example 1: Glitchy lines visible on my website Example 2: A different website using the same text without any glitchy lines. No glitches detected h ...

When using useEffect in React, the handleKeyDown function is causing the output to double with each

Whenever a user inputs something, the output doubles each time, leading to a long loop after just a few inputs. Below is the code snippet: const [direction,setDirection] = useState(Array(1).fill(0)); const directions = ["botNorth","botEa ...

Searching for entries using an array of _id along with other possible column values

const query_id = [1,2,3,4,5,6]; const query_type = "A"; let queries = await Query.find({ _id: query_id, query_type: query_type }); The current code functions as intended, but there may be a better and more elegant way to achieve t ...

The absence of a `require` definition in Typescript combined with daisyui

Considering using typescript with react and daisyUI (a tailwindCSS component). Just a heads up, I'm currently utilizing vite In my ts.config file, I've specified node as moduleResolution Encountering an error in the tailwind config stating &apo ...

Issue with setting value using setState in TypeScript - what's the problem?

Every time I attempt to update the value of currentRole, it appears highlighted in red. Here is a screenshot for reference: const Container: React.FC<ContainerProps> = ({ children }) => { const [role, setRole] = useState<string>(); useE ...

karma - Plugin not located

Attempting to run JS test cases using karma, but consistently receiving a plugin not found error. Oddly enough, the same configuration file works perfectly for one of my co-workers. Below are the logs: $ karma start karma.conf.js 04 10 2016 17:51:24.755 ...

"Why Injecting HttpClient in Angular 4 can be a Game-Changer? Let's

According to the documentation provided by Angular, the HttpClient is injected into the main app component. However, I came across another guide that simply referred to this as a "favorable" practice without providing any explanation. @Component(...) expo ...

The art of linking Observables on the fly in rxjs and angular

In my current project, I am facing a challenge where multiple events can be triggered from an object. These events are handled by a component and then sent to a REST API. The issue arises when I need to ensure that calls to the REST API for a specific reso ...

Troubleshooting the malfunctioning of the Bootstrap slide animation

I've been attempting to implement scroll animation on a div, but for some reason, it's not working as intended. I must have made a mistake somewhere, but I can't figure out where. Any help in resolving this issue would be greatly appreciated ...

"What is the process for developing a Web-component with Vue and typescript that can be used in

Utilizing vue-custom-element, I have successfully created a Web component in Vue and integrated it into Angular. This setup operates seamlessly for Vue+js: import Vue from 'vue' import Calculator from './components/Calculator.vue' impo ...