gpt4 book ai didi

javascript - 从数组中返回与键 :value pair of an object nested in the object I need to return 匹配的对象

转载 作者:行者123 更新时间:2023-12-01 01:13:55 25 4
gpt4 key购买 nike

所需状态

我试图从与特定值匹配的数组中返回一个对象,但我遇到了一些问题,因为该数组包含嵌套在另一个对象中的对象。我想返回整个对象,但我需要搜索的值位于嵌套对象内部。

例如,我尝试根据键:值对“name”:“Kills”的值返回整个对象

 {
"metadata": {
"key": "kills",
"name": "Kills",
"isReversed": false
},
"value": 1364,
"displayValue": "1,364"
}

数组格式

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"
}

]

当前代码不起作用

我不打算使用这种结构的代码,任何有效的解决方案对我来说都很棒,但我需要它成为一个可以重用的函数。

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];
}
}

}

任何帮助将不胜感激!

最佳答案

尝试

stats.find(x=> x.metadata.name=="Kills");

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"
}

]

let r= stats.find(x=> x.metadata.name=="Kills");
console.log(r);

关于javascript - 从数组中返回与键 :value pair of an object nested in the object I need to return 匹配的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54931709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com