关于js取值的问题(新手提问)

滚瓜烂熟
  • 9

刚刚学习js,我获取的数据如下

let json
json = {
    "result": true,
    "data": {
        "id": "1a2b3c4d5e6f7g8h9i",
        "dividedRetList": [
            {
                "memberList": [
                    {
                        "captainId": "259b55"
                    },
                    {
                        "captainId": "259b55"
                    },
                    {
                        "captainId": "259b55"
                    },
                    {
                        "captainId": "259b55"
                    },
                    {
                        "captainId": "259b55"
                    }
                ],
                "aaa": true,
                "bbb": true
            },
            {
                "memberList": [
                    {
                        "captainId": "a86e41"
                    },
                    {
                        "captainId": "a86e41"
                    },
                    {
                        "captainId": "a86e41"
                    },
                    {
                        "captainId": "a86e41"
                    },
                    {
                        "captainId": "a86e41"
                    }
                ],
                "aaa": true,
                "bbb": true
            }
        ],
        "aa": true
    },
    "a": 0,
    "b": "b"
};

现在需要取captainId的值,我用的let of 代码如下:(ps:各位大佬有没有更好的方法,欢迎指点。)

for (let dividedRetList of json.data.dividedRetList) {
    //console.log(dividedRetList);
    for(let memberList of dividedRetList.memberList){
        //console.log(memberList);
        let arr=memberList.captainId
        console.log(arr)
        // 259b55
        // 259b55
        // 259b55
        // 259b55
        // 259b55
        // a86e41
        // a86e41
        // a86e41
        // a86e41
        // a86e41
    }
}

打印出来是一排数组,我需要把这组数组去重,应该怎么做?
最后结果需要变成这样:
[259b55,a86e41]

回复
阅读 465
3 个回答
✓ 已被采纳

[...new Set(json.data.dividedRetList.map(v => v.memberList.map(o => o.captainId)).flat())]
PS: for...of也可以,但是如果用原生方法就用,少写很多代码,另外就是变量命名上要对应,List通常就是数组,Item表示元素,不要命名List确实际是数组元素,给人造成误解

Array.from(new Set(json.data.dividedRetList.map(l => l.memberList.map(m => m.captainId)).flat()))
let arr = [];
for (let { memberList } of json.data.dividedRetList) {
    for(let { captainId } of memberList){
        if (!arr.includes(captainId)) arr.push(captainId);
    }
}
console.log(arr);
宣传栏