2

The object structure is as follows.

object = {
  obj1: {
    obj2: {
       name: 'MY name'
    }
  }
}

This structure is dynamic and sometimes there wont be an obj1.

So, In react you will be writing the code like..

object && obj1 && obj2 && obj2.name

so that only if object, obj1, and obj2 are present then obj2.name will be displayed.

In this case there wont be any undefined error since the presence of each object is checked prior to going inside the function.

Is there alternate way to the above code so that it displays the name when all the objects are present. If not, it should not throw an error.

jo_va
  • 13,504
  • 3
  • 23
  • 47
prajeesh
  • 2,202
  • 6
  • 34
  • 59

4 Answers4

0

Use hasOwnProperty to check if obj1 is present or not

object = {
  obj1: {
    obj2: {
       name: 'MY name'
    }
  }
}
if(object.hasOwnProperty('obj1'))
console.log(object.obj1.obj2.name)
else
console.log(object.obj2.name)
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

Try

object = {
  obj1: {
    obj2: {
       name: 'MY name'
    }
  }
}
    
var name = (object.hasOwnProperty('obj1'))  ? object.obj1.obj2.name : object.obj2.name;
console.log(name);
A. El-zahaby
  • 1,130
  • 11
  • 32
0

You need to check every property before reading a nested one:

const name = object && object.obj1 && object.obj1.obj2 && object.obj1.obj2.name;

This is laborious and verbose as you have to repeat the same thing over and over to access deeply nested properties.

I suggest to use a safeEval function that wraps your potentialy dangerous property access code with a try/catch and returns undefined if an error occurs. This is much shorter than manually checking every property:

const name = safeEval(() => obj.obj1.obj2.name);

Here is an example:

const obj = { obj1: { obj2: { name: 'Hello' } } }

function safeEval(fn) {
  try { return fn(); }
  catch { return undefined; }
}

const a = obj && obj.obj1 && obj.obj1.obj2 && obj.obj1.obj2.name;
const b = safeEval(() => obj.obj1.obj2.name);
const c = safeEval(() => obj.obj1.obj2.obj3.obj4.name);

console.log(a, b, c);
jo_va
  • 13,504
  • 3
  • 23
  • 47
-1

I would recommend writing a recursive function that inspects the object and recurses down its children if a name is found. I see others suggested catching the error- I would advise against abusing exception handling for runtime errors like this.

awhoof
  • 1
  • 1