Retrieve elements with a customized attribute from an array in JavaScript

In my JavaScript code, I have added objects to an array, each with a new property called "Type". Now, I need to extract the objects from the array that have this "Type" property and put them into a new array.

var arr = [
{ID: 1, Name: "Name1"},
{ID: 2, Name: "Name2"}]

var newObject = {
ID: 3,
Name: 'Test',
Type: 'New'
};

arr.push(newObject);

I attempted

var filteredArray = arr.filter(item => item.Type !== null);

However, this code returns all objects from the original array.

The desired result should be

[{ ID: 3, Name: "Test", Type: "New" }]

Answer №1

Avoid checking for null. Opt for using undefined instead:

let latestValue = array.filter(item => item.Type !== undefined);

Take a look at this explanation about null and undefined:

Null: Represents the deliberate absence of a value. It is one of JavaScript's primitive values. Undefined: Indicates that the value is non-existent in the code. It refers to the global object.

Answer №2

The reason for this behavior is that the value is undefined rather than null

The following code snippet will retrieve any data type except for falsy types such as "Type" : 0 and "Type": ""

let items = [
{ID: 1, Name: "Name1"},
{ID: 2, Name: "Name2"}]

var newObj = {
ID: 3,
Name: 'Test',
Type: 'New'
};

items.push(newObj);

const filteredValues = items.filter(item => { 
  console.log(item.Type) 
  return item.Type; // excluding undefined, null, and empty string.
  });
  
console.log(filteredValues)

Answer №3

If you're working with newer versions of Javascript (like ES 2021), there's a handy feature called nullish coalescing:

var arr = [
{ID: 1, Name: "Name1"},
{ID: 2, Name: "Name2"}]

var newObject = {
ID: 3,
Name: 'Test',
Type: 'New'
};

arr.push(newObject);

var newVal = arr.filter(x => x.Type ?? false);
console.log(newVal)

Nullish coalescing comes in handy when a variable is defined, but it evaluates to false. With a ?? b, either a or b will be returned. If a is undefined or null, then b will be returned. Otherwise, a will be returned. For more information, you can check out MDN.

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

What distinguishes defining a function through a prototype versus as a class property?

Check out this code snippet: Apple defines its function using a prototype. Banana defines its function using a class property. var Apple = function(){} Apple.prototype.say = function(){ console.debug('HelloWorld'); } var Banana = functio ...

Looking to retrieve a JavaScript code block from an AJAX response using jQuery?

How can I extract a Javascript code block from an ajax response using jQuery, while disregarding other tags (in this case, the div tag) and prevent the execution or evaluation of the Javascript code? Example in get_js.html: <script> $(function ...

How come this 2-dimensional array is adding elements unexpectedly?

I just realized my error where the tempRndNumber was being reset in the inner loop. Although, I am still encountering an issue where "," characters are appearing in the array. The goal is to create a 2D array that is populated only when a random number me ...

Navigating through JQuery

Is there a way to scroll to a div + 100px specifically on the y axis? I am unsure how to achieve this. Can you provide guidance? I attempted using $.scrollTo('div100' + '100px', 2000) but unfortunately, it did not produce the desired ...

The onClick event in React/NextJS is not functioning properly when applied to an external component

One dilemma I am facing involves my main page and a button component that I have created to be reused throughout my project. Strangely, when I add the onClick event to the external component, the click event does not seem to work. However, if I create the ...

Executing a function when a dropdown in Bootstrap is expanded and closed

How can I use JavaScript to execute a function when clicking on a notification button in a Bootstrap navbar to expand the dropdown, and then close the dropdown when clicking it again? I have tried selecting the dropdown and modifying the click function, b ...

The Angular module instantiation failed with the error message: "[$injector:modulerr] Failed to

Struggling with setting up basic AngularJS functionality for a project, especially when trying to include angular-route. Both components are version 1.4.8. My approach involves using gulp-require to concatenate my JS files. Here is my main javascript file: ...

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me... My goal is to redirect to a URL like this: this.router.navigateByUrl('/products'); I want to pass an array and retrieve it in the component with the active link ...

Concealing the NavBar When Showing a Popup Using React

I am facing a challenge with hiding my bootstrap navbar that has a CSS property of position: sticky-top when I display a pop-up slideshow. I am working with React. I have attempted to target the navbar element in my click handler and adjust the display pro ...

I was assigned to calculate and transfer the length of the string within the parentheses (written in javascript)

function formatString(str) { const formatted = str.split(',') .map(subStr => `${subStr}(${subStr.length})`) .join(', '); return formatted; } The expected output was "hello(5), world(5), abra(4), carabfa(7), r ...

Is there a way for me to display the image name at the bottom before uploading it, and have a new div created every time I upload an image?

Is there a way to display the image name at the bottom and have it create a new div every time an image is uploaded? I would appreciate any help with this... <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstra ...

Is there an issue with JQM plugin due to jQuery's append() function?

I am just starting to learn about jQuery mobile as I develop an app using it. Whenever I click on the Add_details button, I want to add dynamic input fields only once. After saving, if I click on the Add_details button again, I need to append more dynamic ...

Error Message: Node.js EJS 'Is Undefined'

When passing an array to an ejs template using Nodejs, I encountered an issue where it seems we cannot directly pass an array. As a workaround, I tried to receive the value like this: console.log(<%= val %>) The output was: Rec - 159,Rec - 160 Att ...

Issue with VueJS components not functioning as expected with routes

I've encountered an issue when using the component tag with an id of #app within the template of my components/App.vue file. Whenever I include this setup, I receive the following errors: // components/App.vue <template> <div id="app"> ...

Leveraging express functions in Node.js framework

Currently, I am delving into the world of nodeJS and have stumbled upon a great collection of tutorials. The tutorials are focused on teaching me about a powerful framework known as express. In order to utilize express effectively, one must also grasp the ...

Utilizing the Context API in Next.js to transfer a prop from the layout component to its children

I am encountering difficulties utilizing the context API to globally pass a state in my app's layout. Here is the code for the Layout component: import { useState, useEffect, createContext } from 'react' import useAPIStore from "../store/sto ...

What is the best way to change the folder name when hovering over it?

Typically, my website displays categories with images from the /thumb-min/ directory. For example, 95-IMG_6509.JPG is loaded like this: /thumb-min/95-IMG_6509.JPG When I navigate to the details page, it loads the image from: /thumb-medium/95-IMG_6509.JP ...

Unusual trait of TrackballControls.target within the world of Three.js

My current project involves simulating a 3D distribution of galaxies. In this simulation, the galaxies are represented as points. question1.htm references galaxydata1.txt to calculate and load the galaxy positions: rawFile.open("GET", "galaxydata1.txt", ...

Extract several "documents" from one compilation

To easily convert my code into a single module using webpack, I can use the following method: { entry: path.join(__dirname, 'src/index.js'), output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', ...