The basic answer is: No, there isn't a way to do that which is likely to pass your "elegance" test. :-) (I like Sairyu's approach of creating a reusable function [perhaps with a shorter name]. Or you might even make it a Point
class with add
, sub
, etc.)
"Elegant" is a value judgement, but if these are the only properties in the objects and you want to avoid explicitly writing x
and y
, you can use a for..in
loop, a for..of
loop on Object.keys
, or a combination of Object.entries
, map
, and Object.fromEntries
though the overhead on that last one starts looking a bit overkill.
const delta = {};
for (const key in origin) {
delta[key] = origin[key] - coordinates[key];
}
or
const delta = {};
for (const key of Object.keys(origin)) {
delta[key] = origin[key] - coordinates[key];
}
or
const delta = Object.fromEntries(
Object.entries(origin).map(
([key, value]) => [key, value - coordinates[key]]
)
);
But again: None of these is likely to be "elegant" by most definitions I can imagine. :-)