Is it possible to achieve this dynamically without hard-coding key1 and key2? Let's assume they are stored in an array called unwantedKeys, which is determined only at runtime.
Yes, but not completely dynamic. You would need to know the number of keys in advance. For example, for two keys:
const { [unwantedKeys[0]]: unused1, [unwantedKeys[1]]: unused2, ...rest } = obj;
const unwantedKeys = ["key1", "key2"];
const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" };
const { [unwantedKeys[0]]: unused1, [unwantedKeys[1]]: unused2, ...rest } = obj;
console.log(rest);
This approach might not be suitable for your scenario since the length of unwantedKeys is only known at runtime. :-) (Edit: It has been confirmed that the length is indeed only known at runtime.)
Since you require a dynamic solution, syntax alone won't suffice; however, you can utilize standard library tools like Object.entries
, Array.prototype.filter
, and Object.fromEntries
:
const rest = Object.fromEntries(
Object.entries(obj).filter(([key]) => !unwanted.includes(key))
);
const unwantedKeys = ["key1", "key2"];
const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" };
const rest = Object.fromEntries(
Object.entries(obj).filter(([key]) => !unwantedKeys.includes(key))
);
console.log(rest);
Alternatively, with the use of a Set
, particularly if the list of unwantedKeys is extremely long and efficiency is a concern (unlikely :-)):
const unwantedSet = new Set(unwantedKeys);
const rest = Object.fromEntries(
Object.entries(obj).filter(([key]) => !unwantedSet.has(key))
);
const unwantedKeys = ["key1", "key2"];
const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" };
const unwantedSet = new Set(unwantedKeys);
const rest = Object.fromEntries(
Object.entries(obj).filter(([key]) => !unwantedSet.has(key))
);
console.log(rest);