我将如何按其中一个子值对该表进行排序,以及如何从中获得最佳结果? [复制]
Posted
技术标签:
【中文标题】我将如何按其中一个子值对该表进行排序,以及如何从中获得最佳结果? [复制]【英文标题】:How would I sort this table by one of the child values and how would I get the top result from it? [duplicate] 【发布时间】:2021-09-14 18:03:04 【问题描述】:我目前正在制作一个 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 的新手,所以如果这是一个简单的答案,我深表歉意。
【问题讨论】:
【参考方案1】:您可以将对象转换为数组并按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)
【讨论】:
以上是关于我将如何按其中一个子值对该表进行排序,以及如何从中获得最佳结果? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
Android-java-如何按对象内的某个值对对象列表进行排序