-2

TLDR Edit: I was confusing object destructuring w/ arrays and spread syntax. Below edit does the trick to recursively unpack the nested object.

let nextLevel = Object.values(obj)
return goingDeep(...nextLevel)

Following is the original question, which I'll leave up in case another noob such as myself runs into this, help save them from the downvotes ;p
Attempt to destructure a nested object recursively returns undefined. Putting that aside simply trying to destructure the same object into different variables returns undefined.

Keeping it simple, just assuming a single key:value (object) per layer so no need to iterate.

const container = {container1: {container2 : {container3: {container4: 'core'}}}}

Putting recursion aside for the moment the following results with simply two different destructuring assignments...

const {level1} = container
console.log(level1) // => container1: {container2:{ etc
const {level1_different} = container
console.log(level1_different) // => undefined

this is what I attempted with the recursion

const goingDeep = (obj) => {
    if (obj.hasOwnProperty('container4')){
        obj.container4 = 'found'
        return obj
    } else {
       // let {nextLevel} = obj        /no good
       // return goingDeep(nextLevel)  /no good
       let nextLevel = Object.values(obj)
       return goingDeep(...nextLevel)
    }
}

originally had the destructuring at the parameter goingDeep = ({obj}) which I have used successfully for arrays so clearly I'm misunderstanding something(s) fundamental to destructuring objects

  • Your `container` object is invalid, and after fixing that, both of your destructuring assignments will return undefined because you don't have a `level1` or `level1_different` property in your object. – Robby Cornelissen Jun 25 '19 at 03:26

2 Answers2

0
let {nextLevel} = obj

Is the same as

let nextLevel = obj.nextLevel;

I think you might be misunderstanding what destructing does.

To be recursive you will need to dynamically search all properties.

const goingDeep = obj => Object.getOwnPropertyNames(obj).reduce( (prop, result) => result === null ? (obj[prop] === 'core' ? obj : goingDeep(obj[prop])) : result, null );

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
0

You are, indeed, misunderstanding how destructing works. If you have an object, destructing lets you create new variables with the same names as the properties in an object.

let obj = {
  prop1: 'value1',
  prop2: 'value2',
};

let {prop1, prop2, prop3} = obj;
console.log(prop1, prop2, prop3)
Mason
  • 738
  • 7
  • 18
  • 1
    You can also name the variables, you are not restricted to using the property name. – Kobe Jun 25 '19 at 07:56
  • @Kobe oh wow, reading the MDN article now. Destructuring is a lot more powerful than I thought! – Mason Jun 25 '19 at 08:29