gpt4 book ai didi

javascript - 如何使用 javascript 从 JSON 字符串获取特定值

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

我正在使用 JavaScript 从 API 获取数据,我得到的结构如下所示:

[{
"word":"gentleman",
"score":42722,
"tags":["syn","n"]
},
{
"word":"serviceman",
"score":38277,
"tags":["syn","n"]
},
{
"word":"human being",
"score":34153,
"tags":["syn","n"]
},
{
"word":"valet",
"score":31892,
"tags":["syn","n"]
}
// etc...
]

我只想获取与键 word 关联的值这样输出将是:

绅士军人人类等等...

请帮助我循环这些数据,以便我只能得到所需的输出。

index.html:

<form id="initial-word-form">
<input style="float: left;" type="text" name="test" id="synonyms" required>
</form>
<a href="#" id="related-word"></a>
<button id="myBtn" onclick="relatedWordClick()">Find Synonyms</button>
<p id="history"></p>

main.js:

function relatedWordClick (){
event.preventDefault();
const x = document.getElementById("synonyms").value;
document.getElementById("history").innerHTML = x;
fetch("https://api.datamuse.com/words?ml=" + x)
.then((resp) => resp.json())
.then (data =>
{
const obj = JSON.stringify(data);
document.getElementById("history").innerHTML = obj;
})
.catch(err => console.log(err));
}

最佳答案

迭代每个数据对象并将其 word 属性映射到另一个 wordArr。

const wordArr = data.map(obj => obj.word)

wordArr 将如下所示:["gentleman", "human", "etc"]

关于javascript - 如何使用 javascript 从 JSON 字符串获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52369804/

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