javascript - 如何对 JSON 中的数组进行排序以获取特定索引的值?
问题描述
嗨,我对 JSON 和 API 非常陌生,并且正在研究一个 API,在该 API 中我可以在数组中获得价值,例如。
{
id: 0,
text: "one"
}
{
id: 1,
text: "two"
}
{
id: 2,
text: "three"
}
我只想要一个数组的值,id=0
我不知道如何在 JSON 中对数组进行排序来实现这一点,我使用 ajax 来获取这个值
async function getDataFromId() {
let url = 'API_URL';
let Qid = 1;
let result;
try {
result = await jQuery.ajax({
url: url,
type: 'GET',
contentType: 'application/json',
});
result = result.sort((a, b) => a.id- b.id);
console.log(result)
}catch (error) {
console.error(error);
}
}
解决方案
您不需要对数组进行排序以获取 id == 0 的对象。使用 Array#find 找到您想要的对象。
let myObject = myArr.find((_o)=>_o.id === 0);
推荐阅读
- timestamp - 将 .txt 文件中的时间戳值导入 Teradata 表中的等效列(UTC 时间戳)
- node.js - 如何在网站上显示来自 s3 的图像?
- java - 访问变量时线程行为的差异
- lua - (Roblox Studio)客户端-服务器-客户端通信不起作用
- c - 如何计算 devmem2/mmap 的 MMIO GPIO 地址
- scala - 如何约束具有多个约束的类型变量?
- apache - 当使用 apcache.commons 中的 CSVPrinter 时,为什么 close() 方法在 Intellij 中突出显示为冗余?
- ionic-framework - 离子构建失败任务':app:processDebugGoogleServices'的执行失败
- java - .getCurrentUser() 永远不会返回 null - firebase
- haskell - 模板 Haskell on Aeson