2

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 ?

2
  • If you want that, why not just let { data } = animal;? Commented Nov 28, 2019 at 11:33
  • It's not clear what variables you want to end up with. Do you want title and legs, data and typee, or all four? Commented Nov 28, 2019 at 11:41

2 Answers 2

5

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);

Sign up to request clarification or add additional context in comments.

2 Comments

@ Ashwani - You only need the data, and typee, parts of that if you want those variables (as suggested by your console.log(data) statement). If you just want title and legs, just leave data, and typee, out.
Heh, I actually meant the opposite. :-) If they only want title and legs, they can just use {data: {typee: {title, legs } } }. I was basically thinking it was the console.log that was wrong in the question, they did it just for debugging or something, rather than the destructuring. Anyway, good answer, tells them what was going on and, if they want data and typee, how to get them.
0
let {data:{typee:{title,legs}}}=animal;

Creates title and legs not data. If you want to get one of the other encapsulating properties as well you have to specify it separately:

//creates data along with title and legs
let {data, data:{typee:{title,legs}}}=animal;
console.log(data,title,legs);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.