从JSON值实现计数器

时间:2019-07-10 04:49:34

标签: javascript

我正在编写一个接收以下json的云函数

{
    "data":{
        "preference1" : "Food",
        "preference2" : "Travel",
        "preference3" : "Fashion"
}

用户从10个首选项列表中选择了前3个首选项,我想实现计数器,以便我可以跟踪选择最多的那个。

我正在考虑以这样的方式实现计数器:我将声明变量,然后执行一系列if语句,以在与字符串匹配的情况下加+ 1。

var food = 0 
var travel = 0 
var fashion = 0 
if (data.preference1 == 'Food') { 
  var food = 1 
}
if (data.preference1 == 'Travel') { 
  var travel = 1 
}

...等等。

最终做到...

countDoc.ref.update({
  food_count: countDoc.ref.data().food_count + food,
  travel_count: countDoc.ref.data().travel_count + travel,
  fashion_count: countDoc.ref.data().fashion_count + fashion
})

这将使我获得理想的结果,但是我知道必须有一种更干净的方法来做到这一点。我不知道确切如何搜索此问题或尝试哪种方法。

如果我能指出正确的方向,那就太好了。

谢谢。

3 个答案:

答案 0 :(得分:2)

首先,这是一个无效的JSON-尾随逗号(“ Fashion”之后的逗号,其中没有其他元素)在JSON中是非法的。假设这是固定的...

虽然有合理的理由将其表示为JSON形式,但大多数人可能更喜欢采用这种形式:

private routeURL = new Subject<string> ();

canActivate() {
    if (this.authenticationService.currentUserValue) {
        this.getNavigationEnd().then(res => console.log('2 ' + res) );
// I want to get this.getNavigationEnd()'s result[true or false] for router guard's canActivate().

        return true;
    }
    this.router.navigate(['/401']);
    return false;
  }

  async getNavigationEnd() {
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((result) => {
      let value: any;
      value = result;
      this.routeURL.next(value.url);
    });
    const valueArray = this.routeURL.asObservable();
    let bool = false;
    await valueArray.subscribe(value => {
      console.log(value);
      if (this.menuURIarray.includes(value)) {
        bool = true;
      } else {
        bool = false;
      }
    });
    console.log('1 ' + bool);
    return bool;
  }

带有数组,而不是对象的键内包含索引的对象。但是假设你说了什么...

this.menuURIarray

在这里,{ "data": { "preferences": ["Food", "Travel", "Fashion"] } } 等将包含正确的计数。

答案 1 :(得分:2)

您可以使用地图:

const map = new Map()

// For each data item
Object.values(data).forEach((preference) => {
  const count = (map.get(preference) || 0) + 1
  map.set(preference, count)
})

假设您有一组数据项:

const items = [
  {
    preference1: 'Food',
    preference2: 'Travel',
    preference3: 'Fashion',
  },
  {
    preference1: 'Something',
    preference2: 'Travel',
    preference3: 'Fashion',
  },
  {
    preference1: 'Food',
    preference2: 'Something Else',
    preference3: 'Fashion',
  },
]

const map = new Map()

// For each data item
items.forEach((item) => {
  Object.values(item).forEach((preference) => {
    const count = (map.get(preference) || 0) + 1
    map.set(preference, count)
  })
})

console.log(map)

输出:

Map {
  'Food' => 2,
  'Travel' => 2,
  'Fashion' => 3,
  'Something' => 1,
  'Something Else' => 1 }

答案 2 :(得分:0)

如果我正在寻找某事的前三名,我会做类似的事情:

axios.post('/get_product_list', {
               category_id:2,
           })
           .then(function (response) {
                    self.products = response.data.products;
           });

请注意,您可以动态地function Counter(title, start){ this.title = title; this.count = start || 0; this.add = function(){ this.count++; return this; } this.sub = function(){ this.count--; return this; } } var pants = new Counter('pants'), people = new Counter('people'), boxes = new Counter('boxes'), shirts = new Counter('shirts'), food = new Counter('food'), trees = new Counter('trees'), water = new Counter('water'), rain = new Counter('rain'), sun = new Counter('sun'), animals = new Counter('animals'), shelter = new Counter('shelter'); pants.add().add().add(); people.add(); boxes.add().add(); shirts.add().add().add(); food.add().add().add().add().add(); trees.add().add(); water.add().add().add().add().add(); rain.add().add(); sun.add(); animals.add(); shelter.add().add().add().add().add(); var counts = [pants, people, boxes, shirts, food, trees, water, rain, sun, animals, shelter]; counts.sort(function(a, b){ return b.count-a.count; }); var topThree = counts.slice(0, 3); topThree.forEach(function(o){ console.log(o.title); });在DOM上单击以实现所需的结果。