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

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);

Leave a Reply