2

I struggling to figure this one out. In the fiddle below how do i account for when itemChild may not be there? When i remove it i get the following error (index):49 Uncaught TypeError: Cannot read property 'cat' of undefined

const item = {
  name: "firstItem",
  color: "red",
  shape: "square",
  size: "big",
  itemChild: {
    cat: "category1",
    age: "10"
  }
}

let {
  name,
  color,
  shape,
  size,
  itemChild = {},
  itemChild: {
    cat = "",
    age = ""
  }
} = item;

if (itemChild) {
  console.log("Child", cat, age);
} else {
  console.log("Parent", name, color);
}

https://jsfiddle.net/1w68j2cv/2/

prasanth
  • 22,145
  • 4
  • 29
  • 53
blu10
  • 534
  • 2
  • 6
  • 28
  • You need to join the nested target assignment and the default value into the same property element: `itemChild: { cat = "", age = "" } = {}`. Your two `itemChild` targets were separate. – Bergi Mar 19 '20 at 11:39
  • hey thanks, why does the default assignment not go on the element itself?... so when itemChild is undefined it would become {} ? – blu10 Mar 19 '20 at 11:41
  • That's just the syntax: `propertyName: assignmentTarget = defaultValue`. It does exactly that. – Bergi Mar 19 '20 at 12:27

1 Answers1

3

You can use default value

const item = {
  name: "firstItem",color: "red",shape: "square",size: "big",
  itemChild: {
    cat: "category1",
    age: "10"
  }
}

const func = (obj) => {
  let {
    name, color, shape, size,
    itemChild: { cat = "", age = "" } = { cat: 'meow', dog: 'bark'}
  } = obj;
  console.log(name,color,shape,size, cat, age)
}

func(item)

const { itemChild,  ...noItemChild } = item

func(noItemChild)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • how do i check for itemChild existence though like in example? – blu10 Mar 19 '20 at 11:44
  • Default values gets assigned only when itemchild is not there ( undefined ) so you can use this fact to check itemchild was there or not – Code Maniac Mar 19 '20 at 11:57
  • 1
    @blu10 You'll have to split it up in separate statements. Currently `itemChild` has a default value thus is always there. Instead you want to extract it first without default value. `let {name, color, shape, size, itemChild} = obj` then check for the existence of `itemChild`. If you need to extract the properties of `itemChild` you can do `let {cat = "", age = ""} = itemChild` later on. – 3limin4t0r Mar 19 '20 at 11:57
  • 1
    @3limin4t0r thats probably a more concise appraoch, thanks – blu10 Mar 19 '20 at 12:09