Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

321
Visualizações
How to determine if a variable is an empty object, empty array or empty string?

I have an object whose keys can have have values which can be object, string or array.

const obj = {
  key1: 'asdf',
  key2: {},
  key3: ['a','b','c'],
  key4: [],
  key5: '',
}

I have to filter all the keys which are empty i.e empty objects, empty array or empty string.

Is there any other way than writing conditions based on typeof of keys and then checking null ?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Simply use Object.keys()

if (Object.keys(something).length) console.log("Not empty");

This works for all of strings, arrays, and of course, objects.

You can check the Object.keys documentation for more details, specifically, the examples section and the non-object coercion section, which state:

// simple array const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// array-like object const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

and

In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError.

From ES2015 onwards, a non-object argument will be coerced to an object.

// In ES5 Object.keys('foo');  // TypeError: "foo" is not an object

// In ES2015+ Object.keys('foo');  // ["0", "1", "2"]
about 4 years ago · Juan Pablo Isaza Relatório

0

For empty strings simple compare the property to "". comparing for empty objects and empty arrays can be done using comparing the Object.keys of the property length compared to 0.

const obj = {
  key1: 'asdf',
  key2: {},
  key3: ['a','b','c'],
  key4: [],
  key5: '',
}

function filterObject(obj) {
    for (var propName in obj) {
        if (obj[propName] === "" || Object.keys(obj[propName]).length === 0) {
            delete obj[propName];
        }
    }
    return obj;
}

console.log(filterObject(obj));

about 4 years ago · Juan Pablo Isaza Relatório

0

You can easily achieve the result using Object.keys and reduce

Loop over the keys of object obj using Object.keys and set the properties of new object only if it is not empty

You can check for the type of value using typeof operator

1) string: typeof will return string and check for the length property

2) array: You can use Array.isArray and it will return boolean value whether the object is an array or not

3) object: You can first get all keys using Object.keys and then check if there is any property exist on that object or not using length property

Since, arrays are object in JS, so you can directly use

(typeof value === "object" && Object.keys(value).length)

to check where it is an object and if it contain any property or not

You can create a filter as

if (value !== "" && Object.keys(value).length) acc[key] = value;

const obj = {
  key1: "asdf",
  key2: {},
  key3: ["a", "b", "c"],
  key4: [],
  key5: "",
};

const result = Object.keys(obj).reduce((acc, key) => {
  const value = obj[key];
  if (value !== "" && Object.keys(value).length) acc[key] = value;
  return acc;
}, {});

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda