簡體   English   中英

lodash:從對象數組中獲取對象-深度搜索和多個謂詞

[英]lodash: get object from an array of objects - deep search and multiple predicates

我有這個:

objs = {
  obj1 : [{ amount: 5, new: true }, { amount: 3, new: false }],
  obj2: [{ amount: 1, new: true }, { amount: 2, new: false }]
}

我想得到一個new: true對象new: trueamount最大

result = { amount: 5, new: true }
var result = null;
var maxAmount = -1;
for(key in obj) {
    if(obj.hasOwnProperty(key)) {
        for(var i = 0, len = obj[key].length; i < len; i++) {
            if(obj[key][i].new === true && obj[key][i].amount > maxAmount) {
                 maxAmount = obj[key][i].amount;
                 result = obj[key][i];
            }
        }
    }
}
console.log(result);

您仍然需要處理在new為true且有多個最大金額時發生的情況。

使用lodash 4.x:

var objs = {
  obj1 : [{ amount: 5, new: true }, { amount: 3, new: false }],
  obj2: [{ amount: 10, new: true }, { amount: 2, new: false }]
};

var result = _(objs)
  .map(value => value)
  .flatten()
  .filter(obj => obj.new)
  .orderBy('amount', 'desc')
  .first();

的jsfiddle

純JavaScript

 var objs = { obj1: [{ amount: 5, new: true }, { amount: 3, new: false }], obj2: [{ amount: 1, new: true }, { amount: 2, new: false }] } var r = objs.obj1.concat(objs.obj2).filter(e => e.new) .sort((a, b) => a.amount - b.amount).pop(); document.write(JSON.stringify(r)); 

亞歷山大的答案很有效,但我更喜歡功能樣式而不是鏈接樣式

洛達什

result = _.maxBy(_.filter(_.flatten(_.values(objs)), 'new'), 'amount');

DEMO

使用Lodash / fp

result = _.compose(_.maxBy('amount'), _.filter('new'), _.flatten, _.values)(objs);

DEMO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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