Bjork
Bjork

Reputation: 57

Javascript destructuring and function as an object

Could someone possibly help me understand this function and destructuring a little better?

export default ({ names }) => {
  const { 
      people: { 
          children = [] 
        } = {} 
    } = names;
  children.find((child) => child.email);
};

I understand that names is being destructured to extract data stored in objects in order to find the first child in the children's array that has an email address. But what I don't understand is why is this function declared like this ({ names })? Is it because names is an object? Sorry if this is a silly question but I am struggling to understand this.

Upvotes: 2

Views: 197

Answers (1)

Behemoth
Behemoth

Reputation: 9300

Lets break it down:

  • Your function takes in 1 parameter which is an object...
  • ...that object must have a property names.

Then the function destructures the object as follows (const { people: { children = [] } = {} } = names;):

  • First, you destructurize a property called people from the names argument
  • If people doesn't exist, it takes the default value of {}.
  • And finally, it grabs the property children (which are an array of objects) from its parent people.

Next, the function logic with .find()

  • All it does is searching for a child from children from people from names from the argument object that has a property email...
  • ...and returns it. Unfortunately that part is missing in your function code.

So in your snippet, the function actually does absolutely nothing, except to be unnecessarily complicated :P


To wrap things up. This is what your argument to the function could look like:

const argument = {
  names: {
    people: {
      children: [{ email: "[email protected]", name: "thechildtobefound" }],
    }
  }
};

And here's a working sample to try:

const func = ({ names }) => {
  const { people: { children = [] } = {} } = names;
  return children.find((child) => child.email);
};

const argument = {
  names: {
    people: {
      children: [{ email: "[email protected]", name: "thechildtobefound" }],
    },
  },
};

console.log(func(argument));

Upvotes: 1

Related Questions