Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
Filter objects with a specific property from a javascript array

I have inserted objects with a new property(property name - "Type") to a JS array. After that, I need to filter objects with that property(which is "Type") to 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 tried

var newVal = arr.filter(x => x.Type !== null);

it returns all the object from array

result should be

[{ ID: 3, Name: "Test", Type: "New" }]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Don't check for null. Use undefined instead:

var newVal = arr.filter(x => x.Type !== undefined);

Check this definition of null and undefined:

Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript. Undefined: It means the value does not exist in the compiler. It is the global object.

about 4 years ago · Juan Pablo Isaza Report

0

Because it is undefined instead of null

The code below will get any type EXCEPT falsy types like "Type" : 0 and "Type": ""

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

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

arr.push(newObject);

const newVal = arr.filter(x => { 
  console.log(x.Type) 
  return x.Type; // not undefined, not null, not empty string.
  });
  
console.log(newVal)

about 4 years ago · Juan Pablo Isaza Report

0

In newer versions of Javascript (ES 2021 I think), you can use 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 is good for when a variable is defined, but it is technically false. With a ?? b, either a or b will be returned. If a is undefined, null, then b will be returned. Otherwise, a will be returned. You can read more about it on MDN.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!