【问题标题】:increment a value in an array if a match is found如果找到匹配项,则增加数组中的值
【发布时间】:2021-12-31 15:35:51
【问题描述】:

所以我有以下数组

// movie.json
// example output (beautified) from: /createvote movie#1,movie#2,movie#3,movie#4
[
  {
    "label": "movie#1",
    "value": "movie#1",
    "voteCount": 0
  },
  {
    "label": "movie#2",
    "value": "movie#2",
    "voteCount": 0
  },
  {
    "label": "movie#3",
    "value": "movie#3",
    "voteCount": 0
  },
  {
    "label": "movie#4",
    "value": "movie#4",
    "voteCount": 0
  }
]

创建使用

movieListArr.map(x => ({label: x, value: x, voteCount: 0}));
    fs.writeFile("movie.json", JSON.stringify( labelArr ), (err) => {
        if (err)
            console.log(err);
        else {
           console.log("writeFile sucess:");
           console.log(fs.readFileSync("movie.json", "utf8"));
        }
    });

我正在尝试将其与以下内容进行比较

interaction.values[0]; // example output: movie#3

这给了我一个人的投票。

我想要做的是,如果用户投票前:movie#3 我想查看movie.json 并为movie#3 将voteCount 加一。老实说,我已经尝试过寻找解决方案,但我似乎无法解决问题。如果有更好的解决方案,而不是通过.json 文件,我也会全力以赴:)

【问题讨论】:

    标签: javascript node.js json discord.js


    【解决方案1】:

    您可以使用Array.find 查找数组中value 属性为'movie#3' 的项,然后将其递增为voteCount 属性。

    const movies=[{label:"movie#1",value:"movie#1",voteCount:0},{label:"movie#2",value:"movie#2",voteCount:0},{label:"movie#3",value:"movie#3",voteCount:0},{label:"movie#4",value:"movie#4",voteCount:0}];
    
    const choice = 'movie#3'
    
    function vote(movieList, vote){
      movieList.find(e => e.value == vote).voteCount++;
    }
    
    vote(movies, choice)
    
    console.log(movies)

    【讨论】:

    • 正是我想要的,非常感谢。
    • @justsurvivinglol 如果此答案解决了您的问题,请打勾!
    【解决方案2】:

    您可以找到对象并增加计数。

    const movie = movies.find(( label ) => label === selectd);
    
    if (movie) ++movie.voteCount;
    

    【讨论】:

    • 正是我所需要的,非常感谢
    猜你喜欢
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多