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.
Lets break it down:
names.Then the function destructures the object as follows (const { people: { children = [] } = {} } = names;):
people from the names argumentpeople doesn't exist, it takes the default value of {}.children (which are an array of
objects) from its parent people.Next, the function logic with .find()
child from children from people from names from the argument object that has a property email...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: "myemail@mail.com", 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: "myemail@mail.com", name: "thechildtobefound" }],
},
},
};
console.log(func(argument));