Skip to main content

Command Palette

Search for a command to run...

Using Optional Chaining for checking for existence of nested Object key

Published
1 min read
A
I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in

In PHP we can do use isset() for checking the existence of a deeply nested array's key since the beginning of time :

<?php
$p1 = "a9bedbd81019b877";
$p2 = "47bd5f64f7be5578";

$obj =
[
    'people' =>
    [
        $p1 =>
        [
            'first_name' => 'John',
            'last_name' => 'Smith',
            'suffix' => 'Sr',
            'results' => [ 'math' => 82, 'english' => 79, 'science' => 50 ]
        ],

        $p2 =>
        [
            'first_name' => 'Timothy',
            'middle_name' => 'Bob',
            'last_name' => 'Jones'
        ]
    ]
];

if (isset($obj['people'][$p1]['results']['science']))
{
    echo $obj['people'][$p1]['results']['science'];
}
echo "\n";
if (!isset($obj['people'][$p2]['results']['science']))
{
    echo 'Not Found';
}
echo "\n";
?>

There are many solutions to this in JavaScript like the answers given here in StackOverflow.

But I think the best solution lies in ECMA 262 (ES2020) which now all browsers support.

let p1 = "a9bedbd81019b877";
let p2 = "47bd5f64f7be5578";

let obj =
{
    'people' :
    {
        [p1] :
        {
            'first_name': 'John',
            'last_name': 'Smith',
            'suffix': 'Sr',
            'results': { 'math': 82, 'english': 79, 'science': 50 }
        },

        [p2] :
        {
            'first_name': 'Timothy',
            'middle_name': 'Bob',
            'last_name': 'Jones',
        }
    }
}

if (obj?.people?.[p1]?.results?.science)
{
    console.log('science = ', obj?.people?.[p1]?.results?.science);
}

console.log(obj?.people?.[p2]?.results?.science);

Output :

science =  50
undefined