'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 1:[1]
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);
Solution 2:[2]
The procedure is quite simple. What you need to do is this —
- Iterate over each value of the
mappingsobject. - 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! :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
| Solution 2 | Shreyan Das |
