Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

96
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda