Summary
I receive a large JSON object in node--about 10000 lines--from an external API and I'm creating a new, consolidated javascript object with the data I want.
I'm extracting specific key:value pairs from an object, where another key:value pair in the object matches what I'm looking for. The main issue I'm having is that if there is no data for a specific object, that object is not included and the function I wrote to assign the specific data I want to a variable becomes undefined and crashed my node server.
**Example API Response (Abbreviated) ** I commented on the data I'm trying to extract
{
"ApiJSONObject": {
"id": "t4365qewsagsdga4",
"stats": [{
"metadata": {
"key": "kills",
"name": "Kills",
"isReversed": false
},
"value": 6435, //Extract this value and save to specific key in new javascript object
"displayValue": "6,435"
}
],
"segments": [{
"metadata": [{
"key": "segment",
"name": "Segment",
"value": "br.close_solo.season",
"displayValue": null
},
{
"key": "lastPlayedAt",
"name": "Last Played At",
"value": "2018-12-11T16:46:35Z",
"displayValue": "12/11/18 4:46:35 PM"
},
{
"key": "updatedAt",
"name": "Updated At",
"value": "2019-06-10T19:07:00.9143166Z",
"displayValue": "6/10/19 7:07:00 PM"
}
],
"stats": [{
"metadata": {
"key": "kills",
"name": "Kills",
"isReversed": false
},
"value": 1, //extract this value and save to specific key in new javascript object based on metaData[0].value
"displayValue": "1"
},
{
"metadata": {
"key": "matchesPlayed",
"name": "Matches Played",
"isReversed": false
},
"value": 1,
"displayValue": "1"
}
]
}]
}
}
Current Function
I wrote this function, however it breaks my code as stats is undefined if there is no data for that specific statsSegment
function getSegmentStats(statType, playerStats) {
let filteredMetaData = [];
for (var i = 0; i < playerStats.segments.length; i++) {
filteredMetaData = playerStats.segments[i].metadata.filter(
val => val["value"] === statType
);
if (filteredMetaData.length) {
return playerStats.segments[i];
}
}
}
function getStatsFields(value,"br.close_solo.season") {
const stat = statsSegment.stats.find(x => x.metadata.name === value);
return stat.value;
}
const seasonSolo = getSegmentStats("br.close_solo.season", playerStats);
const statsObject = { seasonStats: seasonSolo: getStatsFields("Kills", seasonSolo))