Destructuring key from object

Viewed 49

I'm new to javascript and I was wondering how I can destructure key from the nested object

const user = {
        'name': 'Alex',
        'address': '15th Park Avenue',
        'age': 43,
        skills: {
            "cs-s": ["scss", "tailwind"],
            "js": "react",
        },
    }

        ({ name: n, address: a } = user);

    console.log(`my name is ${n} my ${s} in ${c} is ${s} && ${t}`)
    //expected output is my name is Alex my skills in cs-s is scss and tailwind

I also try to do that but still give me the value and I want the key with full Destructuring if it is possible

const member = {
        name: "Nour",
        skill: {
            "css": "scss",
            js: "React",
        },
    };
    let skillOne = Object.keys(user.skill)[0];
    console.log(skillOne);
    ({ name: n, skill: { [skillOne]: s } } = member);
    console.log(`${n} ${s}`)
1 Answers

Not exactly what you wanted (I think you need extra steps to get object keys), but here is a way:

const user = {
    'name': 'Alex',
    'address': '15th Park Avenue',
    'age': 43,
    skills: {
        "cs-s": ["scss", "tailwind"],
        "js": "react",
    },
}

let { name, address, age, skills: { "cs-s": csSkills, "js": jsSkills } } = user;

//expected output is my name is Alex my skills in cs-s is scss and tailwind
console.log(`my name is ${name} my skills in cs-s is ${csSkills[0]} and ${csSkills[1]}`);

Although I think it's bad practice to destructure two layers of objects.

Related