1

I am running into an issue where in I have a object as below

a = {
   b: {
    c: 10
   }
};

Now this is a dynamic object and can be empty on runtime, like this a = {}, I am trying to read c in ES6 shorthand notation like const {b: {c}} = a;. But getting error every time object is empty. Is there a way I can still use this notation for empty object, like get undefined for c in that case.

I know I can do something like (a.b ? a.b.c : undefined), but i just wanted to know shothand way of doing it.

Gautam
  • 815
  • 6
  • 15

4 Answers4

3

You can do = {} for inner objects:

const a = {
   b: {
    c: 10
   }
};

const f = ({b: {c} = {}}) => console.log(c)

f(a)
f({})

In this case c becomes undefined if the object is empty

Egor Stambakio
  • 17,836
  • 5
  • 33
  • 35
  • This way even if I have value assigned to c: 10, I will always get c as undefined. isn't it? – Gautam Oct 08 '17 at 10:18
  • @RanjeetGautam run my code. When `c` is defined it returns the value; otherwise undefined. – Egor Stambakio Oct 08 '17 at 10:19
  • Yes sorry my apology, it does run but isn't this is like setting default property in method parameter? Actually I wanted to know simple shorthand method to capture c even when b is undefined. – Gautam Oct 08 '17 at 10:22
  • @RanjeetGautam in this case this is the answer: https://stackoverflow.com/a/46630023/7636961 – Egor Stambakio Oct 08 '17 at 10:28
2

you can do

let a = {
   b: {
    c: 10
   }
};

let result = a && a.b && a.b.c;

console.log(result);

it would return the property if it is present, otherwise it would return undefined

marvel308
  • 10,288
  • 1
  • 21
  • 32
0

You might want a general approach, which isn't really terse for shallow structures but saves you compiling out a static sequence of conditionals.

function dive (obj, pz) {
  return pz.reduce((acc, p) => {
    return obj && p in acc ? acc[p] : undefined;
  }, obj);
}

You can use this with arbirary depth

console.log(dive({a:{b:{c:[10,11,12]}}}, ['a', 'b', 'c', 1]))

c.f. this demo

teach stem
  • 132
  • 6
0

Give lodash a shot:

lodash.get(a, 'b.c', FALLBACK_DEFAULT_VALUE);
Ryan Huang
  • 3,849
  • 2
  • 13
  • 11