1

I have the following array of objects:

[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "[email protected]"
"phone": "010-692-6593 x09125",
"website": "anastasia.net"
},...];

I am passed id as 2. I want the index of array of objects where id=2. How can this be done in javascript or jQuery?

3 Answers 3

2

Iterate over the obj with Array#forEach function, if actual index is the same as the given id in the arguments, assign it into the objId variable.

If there's no any objects with given id - function will log -1.

let obj = [{id:1,name:"Leanne Graham",username:"Bret",email:"[email protected]",phone:"1-770-736-8031 x56442",website:"hildegard.org"},{id:2,name:"Ervin Howell",username:"Antonette",email:"[email protected]",phone:"010-692-6593 x09125",website:"anastasia.net"}];

function checkId(obj, id) {
  let objId = -1;
  obj.forEach((v,i) => v.id == id ? objId = i : v);
  console.log(objId);
}

checkId(obj, 2);
checkId(obj, 4);

Another approach, using Array#find and Array#indexOf.

let obj = [{id:1,name:"Leanne Graham",username:"Bret",email:"[email protected]",phone:"1-770-736-8031 x56442",website:"hildegard.org"},{id:2,name:"Ervin Howell",username:"Antonette",email:"[email protected]",phone:"010-692-6593 x09125",website:"anastasia.net"}];

function checkId(obj, id) {
  let objId = obj.indexOf(obj.find((v,i) => v.id == id)) || -1;
  console.log(objId);
}

checkId(obj, 2);
checkId(obj, 4);

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

2 Comments

Can the same function be modified to search for strings as well?
@Arihant Like for a name key instead of id?
0

You can do it by using each function:

var json = [
    {"id":"1","tagName":"apple"},
    {"id":"2","tagName":"orange"},
    {"id":"3","tagName":"banana"},
    {"id":"4","tagName":"watermelon"},
    {"id":"5","tagName":"pineapple"}
];

$.each(json, function(idx, obj) {

  if(obj.id == 2){
    alert(idx);//will alert index where id = 2
  }

});

For more details please visit: https://www.mkyong.com/jquery/jquery-loop-over-json-string-each-example/

Comments

0

This function will return an array of indexes if there is one or more matches:

function getIDs(obj,id) {
  var ret = [];
  obj.forEach((val,i) => val.id == id ? ret.push(i) : val); 
  return(ret);
}
var ids = getIDs(object,2);
console.log(ids);

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.