lodash中的嵌套数组过滤

时间:2017-01-30 14:58:55

标签: javascript filter underscore.js filtering lodash

我有一个像这样的Json -

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

我需要使用以下格式的Lodash过滤并创建一个新的json。我试过_.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
            }
        ]
    ]
}

有没有办法使用lodash和Javascript将Json重组为新格式

1 个答案:

答案 0 :(得分:0)

你不需要过滤器。在重新格式化时需要映射。

你可以链图和展平。在你的情况下

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