Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove multiply dictionary keys from array of dictionaries in JavaScript?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{"First": "Bob"}, {"First": "Amy"}]  

TS Playground

>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 });
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading