I have
let Remove = ["Last", "Gender"];
let Contact = [{"First": "Bob", "Last": "Jim", "Gender": "M"},
{"First": "Amy", "Last": "Christen", "Gender": "F"}];
How I remove multiple keys from the dictionary with the keys I want to remove stored in an array?
To get
[{"First": "Bob"}, {"First": "Amy"}]
>Solution :
You could map the objects and reduce the copy by removing keys.
const remove = ["Last", "Gender"];
const contacts = [
{"First": "Bob", "Last": "Jim", "Gender": "M"},
{"First": "Amy", "Last": "Christen", "Gender": "F"}
];
const removed = contacts.map(contact => {
return remove.reduce((copy, keyToRemove) => {
delete copy[keyToRemove];
return copy;
}, { ...contact });
});
console.log(removed);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Here is a TS implementation. You can use a Record<string, string> type to represent your object.
const remove: string[] = ["Last", "Gender"];
const contacts = [
{"First": "Bob", "Last": "Jim", "Gender": "M"},
{"First": "Amy", "Last": "Christen", "Gender": "F"}
];
const removed = prune(contacts, remove);
console.log(removed);
function prune<TObj extends Record<string, string>>(
records: TObj[], keysToRemove: string[]): TObj[] {
return records.map(contact => {
return keysToRemove.reduce((copy: TObj, keyToRemove: string) => {
delete copy[keyToRemove]; // Remove they key from the copy
return copy;
}, { ...contact });
});
}