首页 > 解决方案 > 如何对 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);
    }
}

标签: javascriptjqueryarraysjson

解决方案


您不需要对数组进行排序以获取 id == 0 的对象。使用 Array#find 找到您想要的对象。


let myObject = myArr.find((_o)=>_o.id === 0);


推荐阅读