簡體   English   中英

如何使用lodash計算對象數組中的多個屬性值?

[英]How to count multiple properties values in array of objects using lodash?

是否可以使用一個變量而不使用_.merge來同時計算namecity

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM