2017-08-11 4 views
0

namecityの両方を、_.mergeを使用せずに1つの変数を使用して数えることは可能ですか?lodashを使ってオブジェクトの配列内の複数のプロパティ値を数えるには?

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} 

答えて

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);

関連する問題