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

Pushing value to array that is the value of an object

I have the following structure:

let mappings = {
    "1002": ["1000", "1003"],
    "2000": ["2001", "2002"]
}

and I want to add this piece of data

const issueTypes = ["4000"]

to each of the arrays of the object keys ending with 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

mappings = {
    "1002": ["1000", "1003", "4000"],
    "2000": ["2001", "2002", "4000"]
}

This is what I have so far:

mappings = Object.keys(mappings).reduce((prev, curr, index) => {
            console.log("prevous", prev)
            console.log("curret", curr)
        return ({
            ...prev, [curr]: //unsure of this part which is kind of crucial
        })}, mappings)

Any help would be really appreciated

>Solution :

Why not just iterate over the values of the object, and push?

const mappings = {
    "1002": ["1000", "1003"],
    "2000": ["2001", "2002"]
}
const issueTypes = ["4000"]
for (const arr of Object.values(mappings)) {
  arr.push(...issueTypes);
}
console.log(mappings);

If it must be done immutably, map the entries of the object to a new array of entries, while spreading the new issueTypes into the value.

const mappings = {
    "1002": ["1000", "1003"],
    "2000": ["2001", "2002"]
}
const issueTypes = ["4000"]
const newMappings = Object.fromEntries(
  Object.entries(mappings).map(
    ([key, arr]) => [key, [...arr, ...issueTypes]]
  )
);
console.log(newMappings);
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