Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructing nested object

I want to use object destructing for simplyfing my code. I am getting data from server and the resolve is object:

data = {
  current: {
     humidity: 73
  }
}

Final function should looks like this, but this does not work:

extractData({data.current.humidity: humidity  }) {
            return { humidity };
        }

extractData(data);

How to do function for this kind of object?

like image 248
Blablabla Avatar asked May 30 '26 12:05

Blablabla


2 Answers

Destructuring patterns are just like object literals, so you don't use a dot, you use nesting (also, the name of the variable referring to the object [data] isn't relevant):

// (I assume this is a method in a class; otherwise, add `function`)
extractData({current: {humidity}}) {
    return { humidity };
}

Live Example:

function extractData({current: {humidity}}) {
    return { humidity };
}

const data = {
  current: {
     humidity: 73
  }
};

console.log(extractData(data));

Note that I've kept your return value there, which is an object with a humidity property. If you just want the value of humidity, don't use {} around it:

// (I assume this is a method in a class; otherwise, add `function`)
extractData({current: {humidity}}) {
    return humidity;
}

Live Example:

function extractData({current: {humidity}}) {
    return humidity;
}

const data = {
  current: {
     humidity: 73
  }
};

console.log(extractData(data));

I assumed you wanted a function, but as Rittoo says, you don't need one if all you want to do is get the value of humidity; see their answer for an example.

like image 107
T.J. Crowder Avatar answered Jun 01 '26 03:06

T.J. Crowder


Or you can simply use following format to get the humidity from the data without calling a function.

const {current: { humidity}} = data;
like image 29
Rittoo Avatar answered Jun 01 '26 03:06

Rittoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!