簡體   English   中英

使用lodash,如何獲得嵌套數組對象的最大長度

[英]Using lodash, how I can get the maximum length of nested array object

我需要從下面提到的對象數組中獲取數據,該數組具有嵌套數組對象的最大長度。 根據我的要求, id : 2 values 有 3 個對象,結果如下所述。

任何人都可以幫助我使用 lodash 或一些 javascript 函數來實現這一點。

樣品請求:

[{
    "id": 1,
    "values": [
        {
            "sub": "fr",
            "name": "foobar1"
        }, 
        {
            "sub": "en",
            "name": "foobar2"
        }
    ]
}, 
{
    "id": 2,
    "values": [
        {
            "sub": "fr",
            "name": "foobar3"
        },
        {
            "sub": "en",
             "name": "foobar4"
        },
        {
                "sub": "ts",
                 "name": "foobar5"
            },
        ]
    }]

預期輸出:

"values": [
        {
            "sub": "fr",
            "name": "foobar3"
        },
        {
            "sub": "en",
             "name": "foobar4"
        },
        {
                "sub": "ts",
                 "name": "foobar5"
            },
        ]
    }]

這可以使用本機 javascript reduce函數來實現,如下所示

var source = [...];
source.reduce((max, cur) => cur.values.length > max.values.length ? cur : max, source[0])

暫無
暫無

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

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