Search code examples
javascriptfunctionoopdestructuring

How to unpack nested data into a function?


I want to pull the income property from an object into a function var:

    let obj1 = {
        x: {
            income: 200,
            sex: 'male'
        },
        y: 'name1'
    };

    function informUserData({
     //what to put here ?
    }){
        return income;
    }
    console.log(informUserData(obj1));// it should be 200

I tried this:

function informUserData({
     x{
         income
     }
    }){
        return income;
    }
    console.log(informUserData(obj1));

Then, I tried this, just to check how to unpack a no-nested property value.

    let obj1 = {
        x: {
            income: 200,
            sex: 'male'
        },
        y: 'name1'
    };

    function informUserData({
     y
    }){
        return y
    }
    console.log(informUserData(obj1)); // name1


Solution

  • I got that the problem was a syntax problem Instead of property property I needed property : property. So:

    
        let obj1 = {
            x: {
                income: 200,
                sex: 'male'
            },
            y: 'name1'
        };
    
        function informUserData({
         x: {income}
        }){
            return income
        }
        console.log(informUserData(obj1))