简体   繁体   中英

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?

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.

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

const {current: { humidity}} = data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM