Blablabla
Blablabla

Reputation: 195

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?

Upvotes: 2

Views: 75

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

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.

Upvotes: 6

Rittoo
Rittoo

Reputation: 29

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

const {current: { humidity}} = data;

Upvotes: 3

Related Questions