Search code examples
javascriptecmascript-6destructuring

How to destructure es6 javascript nested objects


I want to structure object in es6 but not getting results.

let animal ={
      data:{
          typee:{
              title: "Cow",
              legs:4
          }
      }
} 

let {data:{typee:{title,legs}}}=animal;

now console.log(data) giving output Error: data is not defined. What I am doing wrong ?


Solution

  • When destructuring nested objects, the interim values are not assigned to consts/variables. You'll have to assign them explictly:

    const animal = {"data":{"typee":{"title":"Cow","legs":4}}};
    
    const {
      data, // assign the data
      data: {
        typee, // assign the typee
        typee: {
          title,
          legs
        }
      }
    } = animal;
    
    console.log(data, typee, title, legs);