简体   繁体   English

如何从lodash中的数组中获取具有共同属性的对象?

[英]How to get objects with a common property from an array in lodash?

Hello there good Samaritan, i would like to use Lodash and find the user with most books in the array.你好,好撒玛利亚人,我想使用 Lodash 并找到数组中拥有最多书籍的用户。

const books = [ {id:0, name: 'Adam', title: 'xx'}, {id:1, name:'Jack', title:'yy'}, { id: 2, name: 'Adam',title:'zz' } ]

Thanks in advance:)提前致谢:)

function search_book(nameKey, myArray){
    for (var i=0; i < myArray.length; i++) {
        if (myArray[i].book === nameKey) {
            return myArray[i];
        }
    }
}

var array = [
    { book:"deep learning", value:"this", other: "that" },
    { book:"ml", value:"this", other: "that" }
];

var resultObject = search_book("ml", array);

console.log(resultObject)

_.filter(list, { name: 'Adam' }) _.filter(list, { name: 'Adam' })

var group = _.countBy(list, function(item){return item.name});    

That will get the counts of author in the list, then you can sort and find the one with the largest.这将获得列表中作者的数量,然后您可以排序并找到最大的作者。

You can generate a function with lodash's _.flow() :您可以使用 lodash 的_.flow()生成 function :

  1. Count the objects by the name propertyname属性计算对象
  2. Convert the resulting object of the previous step to [key, value] pairs,将上一步生成的 object 转换为 [key, value] 对,
  3. Find the pair with the max value找到具有最大值的对
  4. Get the key (the name)获取密钥(名称)

 const { flow, countBy, toPairs, maxBy, tail, head } = _ const fn = flow( arr => countBy(arr, 'name'), // count by name toPairs, // convert to [key, value] pairs arr => maxBy(arr, tail), // find the max by the value (tail) head // get the key (head) ) const books = [ {id:0, name: 'Adam', title: 'xx'}, {id:1, name:'Jack', title:'yy'}, { id: 2, name: 'Adam',title:'zz' } ] const result = fn(books) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

And the same idea using Lodash/fp :和使用Lodash/fp的相同想法:

 const { flow, countBy, toPairs, maxBy, tail, head } = _ const fn = flow( countBy('name'), // count by name toPairs, // convert to [key, value] pairs maxBy(tail), // find the max by the value (tail) head // get the key (head) ) const books = [ {id:0, name: 'Adam', title: 'xx'}, {id:1, name:'Jack', title:'yy'}, { id: 2, name: 'Adam',title:'zz' } ] const result = fn(books) console.log(result)
 <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

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

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