Home > Mobile >  increment a value in an array if a match is found
increment a value in an array if a match is found

Time:11-22

so i've got the following array

// 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
  }
]

created using

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"));
        }
    });

and with the following I'm trying to compare it to

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

that gives me what a person has voted.

what I'm trying to do is if a user votes something ex: movie#3 I want to look through movie.json and increment voteCount by one for movie#3. I've tried searching for a solution already and honestly, I can't seem to put my finger on it. If there's a better solution to doing this instead of through .json files I'm all ears too :)

CodePudding user response:

You can use Array.find to find the item in the array whose value property is 'movie#3', then increment it's voteCount property.

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You could find the object and increment the count.

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

if (movie)   movie.voteCount;
  • Related