You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算对象数组中键对应值的重复次数

Count Occurrences of Lunch/Dinner Across an Array of Objects

Got it, let's figure out how to tally up the total number of times 'Lunch' and 'Dinner' appear across all your objects. Here are a couple of straightforward approaches in JavaScript:

Approach 1: Nested Loops (Easy to Follow)

This method uses simple loops to iterate through each object and its values, updating counts as we go:

var objects = [ 
  { Ram: 'Lunch', Luv:'Lunch', Rani:'Dinner' }, 
  { Ram: 'Dinner', Luv:'Lunch', Rani:'Dinner' }, 
  { Ram: 'Lunch', Luv:'Dinner', Rani:'Dinner' } 
];

// Initialize our count object with starting values of 0
const mealCounts = { Lunch: 0, Dinner: 0 };

// Loop through each person-object in the array
objects.forEach(personMeals => {
  // Extract just the meal values (e.g., ['Lunch', 'Lunch', 'Dinner'])
  const meals = Object.values(personMeals);
  
  // Loop through each meal and increment the corresponding count
  meals.forEach(meal => {
    if (meal in mealCounts) {
      mealCounts[meal]++;
    }
  });
});

// Convert the count object to JSON format
const result = JSON.stringify(mealCounts);
console.log(result);
// Output: {"Lunch":4,"Dinner":5}

How this works:

  • We start with mealCounts to track our target meals, initialized to 0.
  • objects.forEach() goes through each entry in your array.
  • Object.values() pulls out just the meal values from each object, ignoring the names (Ram, Luv, etc.).
  • We loop over those meal values and increment the count for 'Lunch' or 'Dinner' each time we encounter them.
  • Finally, JSON.stringify() converts our count object into the required JSON string.

Approach 2: Concise Functional Style

If you prefer a more compact version using array methods, this works too:

var objects = [ 
  { Ram: 'Lunch', Luv:'Lunch', Rani:'Dinner' }, 
  { Ram: 'Dinner', Luv:'Lunch', Rani:'Dinner' }, 
  { Ram: 'Lunch', Luv:'Dinner', Rani:'Dinner' } 
];

const mealCounts = objects
  // Flatten all meal values into a single array
  .flatMap(obj => Object.values(obj))
  // Reduce the array to our count object
  .reduce((counts, meal) => {
    if (meal === 'Lunch' || meal === 'Dinner') {
      counts[meal]++;
    }
    return counts;
  }, { Lunch: 0, Dinner: 0 });

console.log(JSON.stringify(mealCounts));
// Output: {"Lunch":4,"Dinner":5}

How this works:

  • flatMap() takes each object's values and combines them into one big array of meals (e.g., ['Lunch', 'Lunch', 'Dinner', 'Dinner', ...]).
  • reduce() iterates over that array, updating the count for each meal and returning the final count object.

Both methods will give you the exact JSON output you need, showing that 'Lunch' appears 4 times and 'Dinner' appears 5 times across all objects.

内容的提问来源于stack exchange,提问作者Aanchal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:00:15