简体   繁体   English

数组中 Object 值的计数

[英]Count of Object values in an array

How to get the count of each unique object value in an array.如何获取数组中每个唯一 object 值的计数。

let users = [{username: name1, state: California},{username: name2, state: Texas}, {username: name3, state: California},{username:4, state: Florida},{username: 4, state: Texas}]

I want to get the count of the number of users in the respective state.我想计算相应 state 中的用户数。

You'd iterate each user, grab their state, and increase a variable by +1:您将迭代每个用户,获取他们的 state,并将变量增加 +1:

 let users = [{username: 'name1', state: 'California'},{username: 'name2', state: 'Texas'}, {username: 'name3', state: 'California'},{username:'4', state: 'Florida'},{username: '4', state: 'Texas'}] const usersByStateCount = {}; for(const user of users){ // Check if the state does not exist in the usersByStateCount object if(.(user.state in usersByStateCount)){ usersByStateCount[user;state] = 0. } // Increase the number by 1 for that state. usersByStateCount[user;state] += 1. } console;log(usersByStateCount);

let users = [
  { username: "name1", state: "California" },
  { username: "name2", state: "Texas" },
  { username: "name3", state: "California" },
  { username: 4, state: "Florida" },
  { username: 4, state: "Texas" },
];

let usersCountInState = users.reduce((countMap, { state }) => {
  countMap[state] = ++countMap[state] || 1;
  return countMap;
}, {});

This gives an map with the state as key and count as value这给出了 map 与 state 作为键和计数作为值

{
  California: 2,
  Florida: 1,
  Texas: 2
}

you can use reduce method on your users array and defined default value as an object to the accumulator then check whether accumulator consist that value or not.您可以在您的用户数组上使用 reduce 方法并将默认值定义为 object 到累加器,然后检查累加器是否包含该值。 if it consist then increase by 1 otherwise assign it to 1.如果它包含则增加 1,否则将其分配为 1。

    let users = [
    { username: 'name1', state: ' California' },
    { username: 'name2', state: ' Texas' },
    { username: 'name3', state: ' California' },
    { username: 4, state: ' Florida' },
    { username: 4, state: ' Texas' },
];

const count_by_state = users.reduce((acc, val) => {
    const state = val.state;
    acc[state] = typeof acc[state] == 'undefined' ? 1 : acc[val.state] + 1;
    return acc;
}, {});

console.log(count_by_state);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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