1

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);
    }
}
4
  • Why do you need to sort it if you only want the value where id=0? Wouldn't filter it be enough? Commented Dec 11, 2020 at 4:52
  • @Turtlean I am sorry this is very noob thing but, how to filter? Commented Dec 11, 2020 at 4:53
  • What is JSON anyway Commented Dec 11, 2020 at 4:54
  • 1
    Try this : var new_array = result.filter(function(i){return i.id == 0}) Commented Dec 11, 2020 at 4:56

4 Answers 4

2

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);

Sign up to request clarification or add additional context in comments.

Comments

2

Maybe this:

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

Comments

2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.