javascript - 我将如何按其中一个子值对该表进行排序,以及如何从中获得最佳结果?
问题描述
我目前正在制作一个 discord.js 机器人,它有助于使用透视 API 进行自动审核。在对透视图的 API 进行 API 调用后,我对每个“属性”进行排序。问题是我剩下这样的事情:
但是,我不确定如何按 对它进行排序summaryScore.value
,然后从中获得最佳结果。任何帮助表示赞赏!这是我当前的代码:
try {
google.discoverAPI(DISCOVERY_URL)
.then(client => {
const analyzeRequest = {
comment: {
text: message.content,
},
requestedAttributes: {
SEVERE_TOXICITY: {
scoreThreshold: 0.85,
},
IDENTITY_ATTACK: {
scoreThreshold: 0.85,
},
THREAT: {
scoreThreshold: 0.85,
},
INSULT: {
scoreThreshold: 0.85,
},
PROFANITY: {
scoreThreshold: 0.85,
},
FLIRTATION: {
scoreThreshold: 0.85,
},
SEXUALLY_EXPLICIT: {
scoreThreshold: 0.85,
},
INCOHERENT: {
scoreThreshold: 0.85,
},
INFLAMMATORY: {
scoreThreshold: 0.85,
},
SPAM: {
scoreThreshold: 0.85,
},
},
languages: ['en'],
};
client.comments.analyze({
key: API_KEY,
resource: analyzeRequest,
},
(err, response) => {
if (err) console.log(err);
else {
complete = false;
if (response.data.attributeScores) {
var array = [response.data.attributeScores]
for (const attributeScore of array) {
console.log(attributeScore)
if (attributeScore.name.summaryScore.value > 0.85) {
message.reply(`your message has been removed for: "${attributeScore.name}".`)
message.delete()
}
}
}
}
});
})
.catch(err => {
console.log(err);
});
} catch (err) {
}
非常感谢!任何帮助表示赞赏!我对javascript很陌生,所以如果这是一个简单的答案,我深表歉意。
解决方案
您可以将对象转换为数组并按summaryScore.value
const obj = {
SEVERE_TOXICITY: {
spanScores: [],
summaryScore: { value: 0.9197861, type: 'PROBABILITY' }
},
PROFANITY: {
spanScores: [],
summaryScore: { value: 0.9844065, type: 'PROBABILITY' }
},
INSULT: {
spanScores: [],
summaryScore: { value: 0.9806645, type: 'PROBABILITY' }
},
}
const array = Object.entries(obj)
.map(([key, value]) => ({id: key, ...value}))
array.sort(
(a, b) => b.summaryScore.value - a.summaryScore.value
)
console.log(`The top one is ${array[0].id} with a value of ${array[0].summaryScore.value}`)
或者,如果您只需要具有最高值的对象,则可以遍历对象条目并检查最高值:
const obj = {
SEVERE_TOXICITY: {
spanScores: [],
summaryScore: { value: 0.9197861, type: 'PROBABILITY' }
},
PROFANITY: {
spanScores: [],
summaryScore: { value: 0.9844065, type: 'PROBABILITY' }
},
INSULT: {
spanScores: [],
summaryScore: { value: 0.9806645, type: 'PROBABILITY' }
},
}
let highest = null
for (let [id, value] of Object.entries(obj)) {
if (!highest || value.summaryScore.value > highest.summaryScore.value)
highest = { id, ...value }
}
console.log(highest)
推荐阅读
- apache-spark - pyspark 从 spark 数据框列创建一个不同的列表并在 spark sql where 语句中使用
- c# - 程序世界生成器生成重叠的地砖 - Unity3D C#
- performance - 如何改进我的 LED 显示屏代码,使其实时反应
- javascript - 我如何使用 Livewire 和 CkEditor 4 传递数据?
- python - 使用列表中的数据更新 JSON 文件中的值
- c# - DataProtectorTokenProvider ValidateAsync 始终为 False
- c# - 当我尝试通过解决方案中的另一个项目访问数据时,为什么数据库无法在我的 .NET Web 应用程序项目中初始化?
- django - 带有条件 WHERE 的 Django3 ListView
- powershell - PowerShell Compare-Object 和 Export-Csv 导出错误数据
- ffmpeg - ffplay -noborder 选项缺少参数