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
CodePudding user response:
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);
CodePudding user response:
The procedure is quite simple. What you need to do is this —
- Iterate over each value of the
mappings
object. - Push the new value
Refer to the following code and adapt —
let mappings = {
"1002": ["1000", "1003"],
"2000": ["2001", "2002"]
}
const issueTypes = ["4000"]
for (const item in mappings) {
mappings[item].push(issueTypes[0])
}
Hope this helps! :)