简体   繁体   中英

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. I tried _.filter but always I am getting undefined error

{
    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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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