将值推送到作为对象值的数组
Pushing value to array that is the value of an object
我有以下结构:
let mappings = {
"1002": ["1000", "1003"],
"2000": ["2001", "2002"]
}
我要添加这条数据
const issueTypes = ["4000"]
每个以这个结尾的对象键数组
mappings = {
"1002": ["1000", "1003", "4000"],
"2000": ["2001", "2002", "4000"]
}
这是我目前拥有的:
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)
任何帮助将不胜感激
为什么不直接遍历对象的值,然后推送?
const mappings = {
"1002": ["1000", "1003"],
"2000": ["2001", "2002"]
}
const issueTypes = ["4000"]
for (const arr of Object.values(mappings)) {
arr.push(...issueTypes);
}
console.log(mappings);
如果必须不可变地完成,将对象的条目映射到一个新的条目数组,同时将新的 issueTypes
传播到值中。
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);
手续很简单。你需要做的是这个—
- 遍历
mappings
对象的每个值。
- 推送新值
参考以下代码适配—
let mappings = {
"1002": ["1000", "1003"],
"2000": ["2001", "2002"]
}
const issueTypes = ["4000"]
for (const item in mappings) {
mappings[item].push(issueTypes[0])
}
希望对您有所帮助! :)
我有以下结构:
let mappings = {
"1002": ["1000", "1003"],
"2000": ["2001", "2002"]
}
我要添加这条数据
const issueTypes = ["4000"]
每个以这个结尾的对象键数组
mappings = {
"1002": ["1000", "1003", "4000"],
"2000": ["2001", "2002", "4000"]
}
这是我目前拥有的:
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)
任何帮助将不胜感激
为什么不直接遍历对象的值,然后推送?
const mappings = {
"1002": ["1000", "1003"],
"2000": ["2001", "2002"]
}
const issueTypes = ["4000"]
for (const arr of Object.values(mappings)) {
arr.push(...issueTypes);
}
console.log(mappings);
如果必须不可变地完成,将对象的条目映射到一个新的条目数组,同时将新的 issueTypes
传播到值中。
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);
手续很简单。你需要做的是这个—
- 遍历
mappings
对象的每个值。 - 推送新值
参考以下代码适配—
let mappings = {
"1002": ["1000", "1003"],
"2000": ["2001", "2002"]
}
const issueTypes = ["4000"]
for (const item in mappings) {
mappings[item].push(issueTypes[0])
}
希望对您有所帮助! :)