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

143
Views
How to check for the existence of dynamic property inside an object?
const result = {
    "MEN": [],
    "WOMEN": [],
    "KIDS TEMP": [
        "BCDEFHJJJJJJ34EEE234",
        "ABCDEFGHIJKL12345678"
    ]
}
const result = {
    "MEN": [],
    "WOMEN": [],
    "CHILDREN TEMP": [
        "BCDEFHJJJJJJ34EEE234",
        "ABCDEFGHIJKL12345678"
    ]
}

I have an object result like above. Sometimes, it may have KIDS TEMP property and sometimes CHILDREN TEMP. Since this property has spaces, I cannot use dot operator to fetch these properties. I want to create a flag if either of KIDS TEMP or CHILDREN TEMP exist. I tried below:-

const part = 'KIDS TEMP' || 'CHILDREN TEMP';
    let check;
    if (result) {
      check = !!(result?.MEN.length !== 0 || result[part].length !== 0);
    }

But the above code breaks when I receive CHILDREN TEMP saying that it cannot read length of undefined. How do I fix this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Object.keys() returns the property names of an object. You can check like this, if an object possesses a certain property:

const result = {
    "MEN": [],
    "WOMEN": [],
    "KIDS TEMP": [
        "BCDEFHJJJJJJ34EEE234",
        "ABCDEFGHIJKL12345678"
    ]
}

console.log(Object.keys(result).includes("KIDS TEMP"));
console.log(Object.keys(result).includes("CHILDREN TEMP"));

If you want to test, if a certain attribute exists, and in case it exists, contains a non-empty array, you can test it like this:

const result = {
    "MEN": [],
    "WOMEN": [],
    "KIDS TEMP": [
        "BCDEFHJJJJJJ34EEE234",
        "ABCDEFGHIJKL12345678"
    ]
}

console.log(result["KIDS TEMP"]?.length > 0);
console.log(result["CHILDREN TEMP"]?.length > 0);

The main problem with your code is that const part = string1 || string2 always evaluates to string1, which is not what you intend to do.

about 4 years ago · Juan Pablo Isaza Report

0

You can use Object's method hasOwnProperty it will return true/false depends on if property exists in object or not.

const result = {
    "MEN": [],
    "WOMEN": [],
    "KIDS TEMP": [
        "BCDEFHJJJJJJ34EEE234",
        "ABCDEFGHIJKL12345678"
    ]
}

console.log(result.hasOwnProperty('KIDS TEMP'),result.hasOwnProperty('CHILDREN TEMP'));

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!