gpt4 book ai didi

javascript - 将对象数组的值拼接成一个句子

转载 作者:行者123 更新时间:2023-12-04 07:30:44 24 4
gpt4 key购买 nike

我有一个 api 响应,如下所示:

"payload": {
"paragraph": {
"id": 2692,
"words": [
{
"id": 21679,
"position": 2,
"translation": {
"text": "something",
"language_name": "english"
},
"transliteration": {
"text": "another",
"language_name": "english"
}
},
{
"id": 21671,
"position": 1,
"translation": {
"text": "Then",
"language_name": "english"
},
"transliteration": {
"text": "fa",
"language_name": "english"
}
},
...
]
}
}
如何从 translation 造句 key 基于 position key 。例如,预期的输出应该是一个对象,如: {line: "Then something"}

最佳答案

首先你需要对你的positions进行排序然后你可以使用 map 加入他们,如下所示。

let words = [
{
"id": 21679,
"position": 2,
"translation": {
"text": "something",
"language_name": "english"
},
"transliteration": {
"text": "another",
"language_name": "english"
}
},
{
"id": 21671,
"position": 1,
"translation": {
"text": "Then",
"language_name": "english"
},
"transliteration": {
"text": "fa",
"language_name": "english"
}
}
]

let word = words
.sort((a, b) => a.position - b.position)
.reduce((word, w) => `${word} ${w.translation.text}`, "");

console.log(word)

关于javascript - 将对象数组的值拼接成一个句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67948943/

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