简体   繁体   中英

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.

{
   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

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.


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

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:

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. In this case: 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 ):

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

All the above answers are good but you are using a variable 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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