繁体   English   中英

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

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

你好,好撒玛利亚人,我想使用 Lodash 并找到数组中拥有最多书籍的用户。

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

提前致谢:)

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' })

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

这将获得列表中作者的数量,然后您可以排序并找到最大的作者。

您可以使用 lodash 的_.flow()生成 function :

  1. name属性计算对象
  2. 将上一步生成的 object 转换为 [key, value] 对,
  3. 找到具有最大值的对
  4. 获取密钥(名称)

 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>

和使用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