简体   繁体   English

将值推送到数组,即 object 的值

[英]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到以此结尾的 object 键的每个 arrays

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任何帮助将非常感激

Why not just iterate over the values of the object, and push?为什么不直接遍历 object 的值,然后推送?

 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.如果必须不可变地完成,则将 map 的条目 object 的条目添加到一个新的条目数组中,同时将新的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);

The procedure is quite simple.程序很简单。 What you need to do is this —你需要做的是——

  • Iterate over each value of the mappings object.遍历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: :)希望这可以帮助: :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM