简体   繁体   English

使用lodash,如何获得嵌套数组对象的最大长度

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

I need to take the data from below mentioned array of object which has maximum length of nested array object.我需要从下面提到的对象数组中获取数据,该数组具有嵌套数组对象的最大长度。 As per below my request, id : 2 values has 3 objects, result will be as mentioned below.根据我的要求, id : 2 values 有 3 个对象,结果如下所述。

Anyone help me using lodash or some javascript function to achieve this.任何人都可以帮助我使用 lodash 或一些 javascript 函数来实现这一点。

Sample Request:样品请求:

[{
    "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"
            },
        ]
    }]

Expected output:预期输出:

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

This can be achieved using the native javascript reduce function as follows这可以使用本机 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