[英]How to count multiple properties values in array of objects using lodash?
是否可以使用一个变量而不使用_.merge
来同时计算name
和city
?
const people = [
{ 'name': 'Adam', 'city': 'London', 'age': 34 },
{ 'name': 'Adam', 'age': 34 },
{ 'name': 'John', 'city': 'London','age': 23 },
{ 'name': 'Bob', 'city': 'Paris','age': 69 },
{ 'name': 'Mark', 'city': 'Berlin','age': 69 },
]
const names = _.countBy(people, (person) => person.name);
const cities = _.countBy(people, (person) => person.city);
console.log(_.merge(names,cities)); // Object {Adam: 2, Berlin: 1, Bob: 1, John: 1, London: 2, Mark: 1, Paris: 1, undefined: 1}
您不需要Lodash,只需使用Array#Reduce
。
const people = [ { 'name': 'Adam', 'city': 'London', 'age': 34 }, { 'name': 'Adam', 'age': 34 }, { 'name': 'John', 'city': 'London','age': 23 }, { 'name': 'Bob', 'city': 'Paris','age': 69 }, { 'name': 'Mark', 'city': 'Berlin','age': 69 }, ] const result = people.reduce((acc, curr) => { acc[curr.name] = acc[curr.name] ? acc[curr.name] + 1 : 1; acc[curr.city] = acc[curr.city] ? acc[curr.city] + 1 : 1; return acc; }, {}); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.