I have a function getData(context)
that holds a lot of information for a particular object.
I also have a function getPos()
that gets a subset of that object. I do not wish to return the whole object.
I was hoping I would be able to do something like the function below.
// Example 1
getPos() {
return { x, y } = getData(this); // Doesn't work
}
After looking at it, I completely understand why it doesn't work. So I changed it into
// Example 2
getPos() {
let { x, y } = getData(this);
return { x, y };
}
And everything now works. But I was wondering if there was a more (one liner) way. I have the feeling I already have the most efficient way. And the only 1 liner way I can think of is to do
// Example 3
getPos() {
return { x: getData(this).x, y: getData(this).y };
}
Which is just a little silly. In the future I will have similar functions, with more than just 2 properties, and with Example 2
I would need to list the properties twice. Once for the destructuring, and again for the new object construction. I guess I am more looking for readability and not having to use extra libraries. I have seen there are ways I could do this with Object.assign()
but I believe this would return a clone of the whole getData()
object and not just a subset.