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

JS: best way to keep track of unique key/value pairings?

I am iterating through objects of font data and want to push or add their postscript name and style as a key/value pair. The postscript name will always be the regular version of the postscript so I need to keep track of the style with it. For example, I want my data structure to look like:

[
   { "Arial-MT", "Bold" },
   { "Arial-MT", "Regular"}
]

While iterating though, if I come across another postscript_name that is Arial-MT and style of either Bold or Regular, I don’t want to add it to my data object. What is the cleanest approach to this?

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

>Solution :

Use an object containing Sets of strings.

const styles = {
    "Ariel-MT": new Set(["Bold", "Regular"])
};

postscript_data.forEach(([postscript_name, postscript_style]) => {
    if (styles[postscript_name]) {
        styles[postscript_name].add(postscript_style);
    } else {
        style[postscript_name] = new Set([postscript_style])
    }
});
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