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

175
Views
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 answers
Answer question

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 Report

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 Report

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 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!