首页 > 解决方案 > 解析Node.js时如何获取数据

问题描述

解析时我得到这个答案:

{ 
    data: { 
        type: 'match',
        id: 'ae825686-8a74-4363-a1d1-402d5a4207d5',
        attributes: { 
            createdAt: '2018-11-20T17:06:52Z',
            titleId: 'bluehole-pubg',
            shardId: 'pc-ru',
            tags: null,
            seasonState: 'progress',
            duration: 1823,
            stats: null,
            gameMode: 'squad-fpp'
        },
    },  
    included: [ 
        { 
            type: 'participant',
            id: '0b1b8f78-bb3e-4c0a-9955-9fdf8e33e5b4',
            attributes: [Object] 
        },
        { 
            type: 'participant',
            id: '85e74b88-125b-4529-8c3f-fd76bd43b9aa',
            attributes: [Object] 
        },
        { 
            type: 'roster',
            id: '6db70dce-b056-4bed-8cc4-6521b83bea50',
            attributes: [Object],
            relationships: [Object] 
        },
        { 
            type: 'roster',
            id: 'a35db9ae-e559-4474-b922-784e3221f484',
            attributes: [Object],
            relationships: [Object] 
        }
    ]
}

我需要获取包含 类型的数据:'roster'和对象内容属性,关系。我该怎么做?我尝试提取数据数组,console.log(included [0]);我从type:'participant' 获取数据。试过了console.log (included [{type: 'roster', relationship}]);作为回应,我收到消息undefined请告诉我如何获取必要的数据。

标签: javascriptnode.js

解决方案


使用Array.prototype.filter()

const response = { 
    data: { 
        type: 'match',
        id: 'ae825686-8a74-4363-a1d1-402d5a4207d5',
        attributes: { 
            createdAt: '2018-11-20T17:06:52Z',
            titleId: 'bluehole-pubg',
            shardId: 'pc-ru',
            tags: null,
            seasonState: 'progress',
            duration: 1823,
            stats: null,
            gameMode: 'squad-fpp'
        },
    },  
    included: [ 
        { 
            type: 'participant',
            id: '0b1b8f78-bb3e-4c0a-9955-9fdf8e33e5b4',
            attributes: [Object] 
        },
        { 
            type: 'participant',
            id: '85e74b88-125b-4529-8c3f-fd76bd43b9aa',
            attributes: [Object] 
        },
        { 
            type: 'roster',
            id: '6db70dce-b056-4bed-8cc4-6521b83bea50',
            attributes: [Object],
            relationships: [Object] 
        },
        { 
            type: 'roster',
            id: 'a35db9ae-e559-4474-b922-784e3221f484',
            attributes: [Object],
            relationships: [Object] 
        }
    ]
}

const arrayWithRoster = response.included.filter(item => item.type === 'roster');

console.log(arrayWithRoster);


推荐阅读