Desired State
I'm trying to return an object from an array that matches a specific value and I'm running into some issues because the array contains objects nested within another object. I want to return the entire object but the value I need to search by is inside the nested object.
For example, I'm trying to return this entire object, based on the value of the key:value pair "name": "Kills"
{
"metadata": {
"key": "kills",
"name": "Kills",
"isReversed": false
},
"value": 1364,
"displayValue": "1,364"
}
Array Format
let stats = [
{
"metadata": {
"key": "kills",
"name": "Kills",
"isReversed": false
},
"value": 1364,
"displayValue": "1,364"
},
{
"metadata": {
"key": "score",
"name": "Score",
"isReversed": false
},
"value": 413743,
"displayValue": "413,743"
},
{
"metadata": {
"key": "matchesPlayed",
"name": "Matches Played",
"isReversed": false
},
"value": 2160,
"displayValue": "2,160"
}
]
Current Code that isn't working
I'm not set on using code of this structure, any solution that works is great for me but I need it to be a function I can reuse.
function getStatsFields(value, statsSegment){
console.log('getStatsFields ran', statsSegment.stats[0].metadata.name);
console.log('statsSegment.stats.length', statsSegment.stats.length);
var filteredStats = []
for(var i=0; i < statsSegment.stats.length; ++i){
const killsKey = Object.keys(statsSegment.stats[i].metadata.name)
console.log('killsKey', killsKey);
filteredStats = statsSegment.stats.filter(val => val[killsKey] === value)
console.log('filteredStats before if', filteredStats);
if(filteredStats.length){
console.log('filteredStats[i]', filteredStats[i]);
return filteredStats[i];
}
}
}
Any help would be greatly appreciated!