Ankit
Ankit

Reputation: 1362

How can I perform destructuring in the following code properly

I was learning destructuring and got stuck when both the key and value of the object are strings.

This is the App.js and here I am destructuring the object, I am getting a syntax error.

I have commented the line where I am getting an error

import "./styles.css";
const info = {
  name: "Ankit Singh Chauhan", 
  standard : 12 , 
  subjects : {
    sub1 : "Maths" , 
    sub2 : "Science" , 
    sub3 :{
      "sub3.1" : "ballleballe" , 
      "sub3.2" : "AdvancePhysics",
    }
  }
}
export default function App() {
  const {name ,standard ,subjects} = info ;
  const {sub1 , sub2 , sub3} =  subjects;
  // const { "sub3.1" , "sub3.2"} = sub3 ; 
  return (
      <>
      <div>
        <h3> Hi my name is {name} and I study in class {standard} my favourite subjects are 
           {sub1} and {sub2}</h3>  
        <h1> And the advance one are {sub3["sub3.1"]} and {sub3.["sub3.2"]}  </h1>     
      </div>
      </> 
  );
}

Can you suggest me some edits?

Upvotes: 2

Views: 57

Answers (2)

oalva-rez
oalva-rez

Reputation: 86

Object.keys returns an array of keys. You then destructure these keys into thier respective variable names.

const [ sub3key1, sub3key2 ] = Object.keys(sub3);

You can then reference their values like so:

console.log(sub3[sub3key1], sub[sub3key2]) 
// returns "ballleballe" "AdvancePhysics"

Suggestion: A clean way to turn sub3.1 to a non string property name is sub3_1

Upvotes: 0

tenshi
tenshi

Reputation: 26327

You can still destructure the keys but you have to rename them into a valid identifier:

const { "sub3.1": sub3dot1, "sub3.2": sub3dot2 } = sub3;

Upvotes: 1

Related Questions