简体   繁体   English

如何对 JSON 中的数组进行排序以获得特定索引的值?

[英]How to sort array in JSON to get value of specific index?

Hi I am very new to JSON and API, and working on an API in which I am getting value in an array eg.嗨,我对 JSON 和 API 非常陌生,并且正在研究 API,其中我在数组中获得价值,例如。

{
   id: 0,
   text: "one"
}
{
   id: 1,
   text: "two"
}
{
   id: 2,
   text: "three"
}

I want the value of only of an array where id=0 and i don't know how to sort array in JSON to achieve this, I used ajax to fetch this value我只想要一个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);
    }
}

You don't need to sort the array to get object where id == 0. Use Array#find to find you desire object.您无需对数组进行排序即可获得 object,其中 id == 0。使用 Array#find 查找所需的 object。


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

Maybe this:也许是这样:

 if(result){ resultSorted = result.sort((a, b) => a.id - b.id); resultFiltered = result.filter(x => x.id == 0); }

I want the value of only of an array where id=0我只想要 id=0 的数组的值

You're properly sorting the result in ascendant order according to their ID's, so the only thing left is creating an array that only contains the first element:您正在根据其 ID 按ascendant order正确排序结果,因此唯一剩下的就是创建一个仅包含第一个元素的数组:

result = result.sort((a, b) => a.id- b.id)
console.log([result[0])

You can take advantage of the condition that you are after to filter the array.您可以利用您所追求的条件来filter数组。 In this case: id === 0 .在这种情况下: id === 0 That will remove the elements that doesn't match the condition ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter ):这将删除不符合条件的元素( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter ):

result = result.filter((a) => a.id === 0)
console.log(result)

Bear in mind that sorting an array is more expensive that just filtering it, so if you're only interested in keeping the one with id === 0 I'd definitely go for the filter option请记住,对数组进行sorting比仅filtering它更昂贵,因此,如果您只想保留id === 0的数组,我肯定会选择 go 作为filter选项

All the above answers are good but you are using a variable Qid以上所有答案都很好,但您使用的是变量Qid

result = result.filter(function(i){return i.id === Qid});
console.log(resulr)

You don't need to sort it you can filter this, That will be more easy stuff for your work你不需要排序你可以过滤这个,这对你的工作来说会更容易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM