简体   繁体   English

Lodash中的嵌套数组过滤

[英]Nested array filtering in lodash

I have a Json Like this - 我有这样的杰森-

[
    {
        "place": 1,
        "player": {
            "playerId": 733234,
            "firstName": "cheng",
            "lastName": "w",
            "country": {
                "countryId": 13,
                "name": "China",
                "abbreviation": "CHN"
            }
        },
        "rounds": [
            {
                "roundNumber": 1,
                "startHole": 1
            },
            {
                "roundNumber": 2,
                "startHole": 10,
            },
            {
                "roundNumber": 3,
                "startHole": -1,
                "courseId": 950
            },
            {
                "roundNumber": 4,
                "startHole": -1,
                "courseId": 950
            }
        ]
    },
    {
        "place": 2,
        "player": {
            "playerId": 392990,
            "firstName": "Matt",
            "lastName": "Harmon",
            "country": {
                "countryId": 1,
                "name": "United States",
                "abbreviation": "USA"
            }
        },
        "rounds": [
            {
                "roundNumber": 1,
                "startHole": 1
            },
            {
                "roundNumber": 2,
                "startHole": 10,
            }
        ]
    }
]

I need to filter and create a new json using Lodash in the below format. 我需要使用Lodash过滤和创建以下格式的新json。 I tried _.filter but always I am getting undefined error 我试过_.filter但总是出现未定义的错误

{
    rounds: [
        [
            {
                player Name: "cheng",
                roundNumber: 1
                starthole: 1
            },
            {
                player Name: "math",
                roundNumber: 1
                starthole: 1
            }
        ],
        [
            {
                roundNumber: 2
                player Name: "cheng",
                starthole: 2
            },
            {
                roundNumber: 2
                player Name: "math",
                starthole: 2
            }
        ]
    ]
}

Is there any way to restructure the Json to new format using lodash and Javascript 有什么办法可以使用lodash和Javascript将Json重组为新格式

You dont need filter. 您不需要过滤器。 You need mapping as you are reformatting. 重新格式化时需要映射。

You can chain map and flatten. 您可以链接地图和展平。 In Your case 就你而言

let modifiedArray=_(YOURARRAYHERE).map(s=>{
    let x=_.map(s.rounds,a=>{
        return {
            roundNumber:a.roundNumber,
            startHole:a.startHole,
            playerName:s.player.firstName
        }
    });
    return x;
}).flatten().value();

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

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