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

179
Visualizações
check the existence of a key in associative arrays

Tell me, how correctly to check the existence of a key in associative arrays?

For example:

var mydata = {
    key1: '',
    key2: {
        subkey1: {
            subkey1_1: {
                value1: ''
                value2" '',
            },
        },
        subkey2: '';
    },
}

if ((mydata.key2 != undefined) && (mydata.key2.subkey1 != undefined) && (mydata.key2.subkey1.subkey1_1 != undefined))
    mydata.key2.subkey1.subkey1_1.value1 = 'test';

Too long and confusing

((mydata.key2 != undefined) && (mydata.key2.subkey1 != undefined) && (mydata.key2.subkey1.subkey1_1 != undefined))

I would like to use a simpler function, like

safeSet(mydata.key2.subkey1.subkey1_1.value1, 'test');

or

if (is_undefined(mydata.key2.subkey1.subkey1_1.value1) == true)
    mydata.key2.subkey1.subkey1_1.value1 = 'test'; // now - error if 'mydata.key2.subkey1.subkey1_1' not exist
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can create custom function using reduce() to test if nested property exists. You can just pass key as string.

var mydata = {
  key1: '',
  key2: {
    subkey1: {
      subkey1_1: {
        value1: '',
        value2: '',
      },
    },
    subkey2: ''
  },
}

function safeSet(key, data) {
  return key.split('.').reduce(function(r, e) {
    return r ? r[e] : undefined;
  }, data) != undefined
}

console.log(safeSet('key2.subkey1.subkey1_1.value1', mydata))

over 4 years ago · Santiago Trujillo Relatório

0

You should use the in operator:

"key" in obj // true, regardless of the actual value

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

obj.hasOwnProperty("key") // true

hope this would help you.

Source: http://www.advancesharp.com/questions/628/checking-if-an-associative-array-key-exists-in-javascript

over 4 years ago · Santiago Trujillo Relatório

0

Alternatively, you can make use of the .has() method of Lodash. Then, you would only need to check:

if (_.has(mydata, 'key2.subkey1.subkey1_1.value1')
    mydata.key2.subkey1.subkey1_1.value1 = 'test';
over 4 years ago · Santiago Trujillo 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