简体   繁体   中英

Can I save a conditional in a javascript-object?

I'm sorting through an array of objects based on a various conditionals.

I want to count each object for the various conditionals and I'm not sure how I should achivie this. Could I somehow add conditionals to an object:

var conversions = [
  {
    name: "Användare",
    conditional: conversion.time_gap > 0,
    count: 0,
  }
]

and then loop through and test them:

_.each(user.apilog, function(event){
    _.each(conversions, function(conversion){
      if(conversion.conditional){
        conversion.count++;
      }
    })
})

This wont work, because time_gap is a variable inside user.apilog and is not defined, but something like this.

You could use a function:

var conversions = [
  {
    name: "Användare",
    conditional: function(v) { return (v > 0); },
    count: 0,
  }
]

called as:

_.each(user.apilog, function(event){
   _.each(conversions, function(conversion){
      if(conversion.conditional(time_gap)){
        conversion.count++;
      }
   })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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